如何在Node.js的index.js中自动分配ID并写入posts.json,添加输入字段?
解决Node.js写入posts.json并自动分配ID的POST接口问题
核心实现步骤
1. 完善后端POST接口逻辑
确保项目已安装express,以下是补充完整POST写入逻辑的index.js代码:
const express = require('express'); const fs = require('fs').promises; const path = require('path'); const app = express(); const PORT = 3000; // 解析JSON和表单编码的请求体 app.use(express.json()); app.use(express.urlencoded({ extended: true })); // 已实现的GET接口(读取、查询帖子) app.get('/posts', async (req, res) => { try { const postsPath = path.join(__dirname, 'posts.json'); const data = await fs.readFile(postsPath, 'utf8'); const posts = JSON.parse(data); if (req.query.title) { const filteredPosts = posts.filter(post => post.title.toLowerCase().includes(req.query.title.toLowerCase()) ); return res.json(filteredPosts); } res.json(posts); } catch (err) { res.status(500).json({ error: 'Failed to read posts' }); } }); // 新增POST接口:写入帖子并自动分配ID app.post('/posts', async (req, res) => { try { const { title, content } = req.body; // 验证必填字段 if (!title || !content) { return res.status(400).json({ error: 'Title and content are required' }); } const postsPath = path.join(__dirname, 'posts.json'); // 读取现有帖子数据 const data = await fs.readFile(postsPath, 'utf8'); const posts = JSON.parse(data); // 生成唯一ID:取现有最大ID+1,无数据则设为1 const newId = posts.length > 0 ? Math.max(...posts.map(post => post.id)) + 1 : 1; const newPost = { id: newId, title, content, createdAt: new Date().toISOString() }; // 追加新帖子并写入文件 posts.push(newPost); await fs.writeFile(postsPath, JSON.stringify(posts, null, 2), 'utf8'); res.status(201).json(newPost); } catch (err) { console.error(err); res.status(500).json({ error: 'Failed to create post' }); } }); // 提供前端提交表单页面 app.get('/', (req, res) => { res.send(` <!DOCTYPE html> <html> <head> <title>Create New Post</title> </head> <body> <h1>Add a New Post</h1> <form method="POST" action="/posts"> <div style="margin: 10px 0;"> <label>Title:</label> <input type="text" name="title" required style="margin-left: 10px; padding: 4px;" /> </div> <div style="margin: 10px 0;"> <label>Content:</label> <textarea name="content" rows="5" required style="margin-left: 5px; padding: 4px; width: 300px;"></textarea> </div> <button type="submit" style="padding: 6px 12px;">Submit Post</button> </form> </body> </html> `); }); app.listen(PORT, () => { console.log(`Server running on http://localhost:${PORT}`); });
2. 关键逻辑说明
- 请求体解析:同时支持JSON和表单编码格式的请求,覆盖前端表单提交和API调用两种场景。
- ID生成:通过取现有帖子的最大ID加1保证唯一性,避免重复;空数据时默认ID为1。
- 文件操作:使用
fs.promises异步方法,避免阻塞事件循环;写入时格式化JSON,保证可读性。 - 输入验证:拦截空标题或正文的请求,返回明确的错误提示。
3. posts.json初始格式示例
确保你的posts.json初始结构正确,比如:
[ { "id": 1, "title": "First Post", "content": "This is my first blog post.", "createdAt": "2024-05-20T12:00:00.000Z" } ]
4. 测试方式
- 安装依赖:
npm install express - 启动服务:
node index.js - 访问
http://localhost:3000,通过表单提交新帖子,或用curl测试API:
curl -X POST -H "Content-Type: application/json" -d '{"title":"Test Post","content":"Hello World"}' http://localhost:3000/posts
内容的提问来源于stack exchange,提问作者Ričards Bainors
相关产品推荐
相关产品推荐

