【发布时间】:2023-01-11 08:31:22
【问题描述】:
我想在我的 posts.json 文件中写入数据并抛出 index.js node.js 文件,并且该 id 会自动提供给发布。
这是 index.js 文件:
const { ALL } = require('dns');
const { text } = require('express');
const express = require('express');
const fs = require('fs')
const app = express();
app.get('/', (req, res) => {
res.send('To see all posts add to url /api/posts.')
});
app.get('/api/posts', (req, res) => {
fs.readFile('posts.json', 'utf8', (err, data) => {
if (err) {
console.error(err);
}else{
res.json(JSON.parse(data))};
});
});
app.get('/api/posts/:id', (req, res) => {
fs.readFile('posts.json', 'utf8', (err, data) => {
if (err) {
console.error(err);
}else{
const resArray = JSON.parse(data)
const posts = resArray.find(posts => posts.id == req.params.id)
res.send(posts)
}});
});
app.post('/api/posts', (req, res) => {
fs.writeFile('posts.json', 'utf8', (err, data) => {
if (err) {
console.error(err);
}else{
// here should go the code
}});
});
app.listen(3000, () => {
console.log('server started');
});
我尝试了很多变体,但没有一个起作用。 这是 posts.json 文件部分:
[
{
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
},
{
"id": 2,
"title": "qui est esse",
"body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
},
...
]
我需要一个选项卡中的字段,用于在所有帖子下输入标题和正文。
【问题讨论】:
-
writeFile的第二个参数应该是你要写入的数据,第三个参数是选项。 see Node.js doc
标签: javascript node.js json