gpt4 book ai didi

json - NodeJS接收POST请求并编辑JSON文件

转载 作者:太空宇宙 更新时间:2023-11-04 00:36:50 25 4
gpt4 key购买 nike

在 NodeJS 中收到客户端的 POST 请求后,无法弄清楚如何编辑我的 json 文件。

使用 webix 数据表。在我更新表中的数据后,它会发送一个包含数据+操作的 POST 请求( webix_operation=update/delete/insert ),所以我想我可以做这样的事情:

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended : true }));

app.post("/Page2", function (req, res) {
var operation = req.body.webix_operation;

if (operation == 'update') {
fs.readFile("JSON/DB.json", "utf8", function (err, data) {
var allData = JSON.parse(data)
var userData = {
"id": req.body.id,
"data1": req.body.data1,
"data2": req.body.data2,
"data3": req.body.data3,
}
allData.push(userData);
var newData = JSON.stringify(allData);
fs.writeFile("JSON/DB.json", newData, "utf8");
console.error(err.stack);
})
res.send();
}
else if (operation == 'insert') {
}
else if (operation == 'delete') {

}
else
console.log("This operation is not supported")
});

但是这不起作用。

有人可以检查代码并找出我做错了什么吗?

最佳答案

app.post("/Page2", function (req, res, next) {
var operation = req.body.webix_operation;

if (['insert', 'update', 'delete'].indexOf(operation) == -1)
return next(new Error('Bad request'));

// More better use http post to insert, put to update, delete to delete
// e.g. app.put('/page2', func) to update

var userData = {
id: req.body.id,
data1: req.body.data1,
data2: req.body.data2,
data3: req.body.data3
}

if (!userData.id)
return next(new Error('id is not set'));

fs.readFile("JSON/DB.json", "utf8", function (err, data) {
if (err)
return next(err);

var allData;
try {
allData = JSON.parse(data);
} catch(err) {
return next(err);
}

// find index of element in allData
var i = allData.reduce(function(iRes, e, iCurr) {
return (e.id == userData.id) ? iCurr : iRes
}, -1);

if (i == -1 && (operation == 'update' || operation == 'delete'))
return next(new Error(operation + ': Bad id'));


if (operation == 'update')
allData[i] = userData;

if (operation == 'delete')
allData.splice(i, 1);

if (operation == 'insert')
allData.push(userData);

fs.writeFile("JSON/DB.json", JSON.stringify(allData), 'utf8', function (err) {
if (err)
return next(err);

res.end();
})
}); // end of readFile
});
...
app.use(function(err, req, res, next)) {
console.log(req.url, err);
res.end(err.message);
}

关于json - NodeJS接收POST请求并编辑JSON文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38629156/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com