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

时间:2016-07-28 06:58:05

标签: json node.js post webix

在我从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")
});

但它不起作用。

有人可以查看代码,也许可以弄清楚我做错了什么?

1 个答案:

答案 0 :(得分:1)

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); 
}