要使用 Next.js 构建具有后端和前端的博客应用程序,用户可以在其中添加和删除博客,并将数据存储在数据库中,请按照以下步骤操作:
首先,如果您还没有创建一个新的 Next.js 项目:
npx create-next-app@latest blog-app cd blog-app npm install
对于这个项目,我们通过Mongoose使用MongoDB作为数据库。
npm install mongoose
使用 MongoDB Atlas 等服务创建 MongoDB 数据库或使用本地 MongoDB 设置。
通过创建 lib/mongodb.js 文件连接到 MongoDB:
// 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;
将 MONGODB_URI 添加到您的 .env.local 文件中:
MONGODB_URI=mongodb srv://: @cluster0.mongodb.net/blog-app?retryWrites=true&w=majority
在 models/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);
在Next.js中,您可以在pages/api目录中创建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 (); }Blog App
Blogs
{blogs.map(blog => (
- ))}
{blog.title}
{blog.content}
运行您的应用程序:
npm run dev
如果您需要更多详细信息,请告诉我!
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3