Untuk membina apl blog menggunakan Next.js dengan kedua-dua bahagian belakang dan bahagian hadapan, di mana pengguna boleh menambah dan memadam blog serta menyimpan data dalam pangkalan data, ikut langkah berikut:
Mula-mula, buat projek Next.js baharu jika anda belum berbuat demikian:
npx create-next-app@latest blog-app cd blog-app npm install
Untuk projek ini, mari gunakan MongoDB melalui Mongoose sebagai pangkalan data.
npm install mongoose
Buat pangkalan data MongoDB menggunakan perkhidmatan seperti MongoDB Atlas atau gunakan persediaan MongoDB setempat.
Sambung ke MongoDB dengan mencipta fail lib/mongodb.js:
// lib/mongodb.js import mongoose from 'mongoose'; const MONGODB_URI = process.env.MONGODB_URI; if (!MONGODB_URI) { throw new Error('Please define the MONGODB_URI environment variable'); } let cached = global.mongoose; if (!cached) { cached = global.mongoose = { conn: null, promise: null }; } async function dbConnect() { if (cached.conn) { return cached.conn; } if (!cached.promise) { cached.promise = mongoose.connect(MONGODB_URI).then((mongoose) => { return mongoose; }); } cached.conn = await cached.promise; return cached.conn; } export default dbConnect;
Tambahkan MONGODB_URI pada fail .env.local anda:
MONGODB_URI=mongodb+srv://<username>:<password>@cluster0.mongodb.net/blog-app?retryWrites=true&w=majority
Buat model untuk blog dalam model/Blog.js:
// models/Blog.js import mongoose from 'mongoose'; const BlogSchema = new mongoose.Schema({ title: { type: String, required: true, }, content: { type: String, required: true, }, }, { timestamps: true }); export default mongoose.models.Blog || mongoose.model('Blog', BlogSchema);
Dalam Next.js, anda boleh mencipta laluan API dalam direktori halaman/api.
// pages/api/blog/index.js import dbConnect from '../../../lib/mongodb'; import Blog from '../../../models/Blog'; export default async function handler(req, res) { const { method } = req; await dbConnect(); switch (method) { case 'GET': try { const blogs = await Blog.find({}); res.status(200).json({ success: true, data: blogs }); } catch (error) { res.status(400).json({ success: false }); } break; case 'POST': try { const blog = await Blog.create(req.body); res.status(201).json({ success: true, data: blog }); } catch (error) { res.status(400).json({ success: false }); } break; default: res.status(400).json({ success: false }); break; } }
// pages/api/blog/[id].js import dbConnect from '../../../lib/mongodb'; import Blog from '../../../models/Blog'; export default async function handler(req, res) { const { method } = req; const { id } = req.query; await dbConnect(); switch (method) { case 'DELETE': try { const blog = await Blog.findByIdAndDelete(id); if (!blog) { return res.status(400).json({ success: false }); } res.status(200).json({ success: true, data: {} }); } catch (error) { res.status(400).json({ success: false }); } break; default: res.status(400).json({ success: false }); break; } }
// pages/index.js import { useState, useEffect } from 'react'; import axios from 'axios'; export default function Home() { const [blogs, setBlogs] = useState([]); const [title, setTitle] = useState(''); const [content, setContent] = useState(''); useEffect(() => { async function fetchBlogs() { const response = await axios.get('/api/blog'); setBlogs(response.data.data); } fetchBlogs(); }, []); const addBlog = async () => { const response = await axios.post('/api/blog', { title, content }); setBlogs([...blogs, response.data.data]); setTitle(''); setContent(''); }; const deleteBlog = async (id) => { await axios.delete(`/api/blog/${id}`); setBlogs(blogs.filter(blog => blog._id !== id)); }; return ( <div> <h1>Blog App</h1> <form onSubmit={(e) => { e.preventDefault(); addBlog(); }}> <input type="text" value={title} onChange={(e) => setTitle(e.target.value)} placeholder="Blog Title" /> <textarea value={content} onChange={(e) => setContent(e.target.value)} placeholder="Blog Content" /> <button type="submit">Add Blog</button> </form> <h2>Blogs</h2> <ul> {blogs.map(blog => ( <li key={blog._id}> <h3>{blog.title}</h3> <p>{blog.content}</p> <button onClick={() => deleteBlog(blog._id)}>Delete</button> </li> ))} </ul> </div> ); }
Jalankan aplikasi anda:
npm run dev
Beri tahu saya jika anda memerlukan butiran lanjut!
Atas ialah kandungan terperinci Apl Blog JS seterusnya. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!