Node JS + Put请求没有正文

时间:2018-07-18 10:31:01

标签: node.js api atom-editor put

我开始探索NodeJS并研究API的示例。我可以在发布请求中获得req.body,并且运行正常,但是当我创建要放置的函数时,我的req.body就像{}一样空了。 我的代码如下:

发布请求有效:

router.post('/',  function(req, res) {
   const name = req.body.username
   const address = req.body.address
   const phone = req.body.phone
   const values = [name, address, phone]
   const sql = "INSERT INTO userInfo (username, address, phone) VALUES (?, ?, ?)";
   res.locals.connection.query(sql, values, function (error, results, fields) {
            if(error){
                res.send(JSON.stringify({"status": 500, "error": error, "response": null}));
            } else {
                const value = {"status":"success", "userId": results.insertId}
                res.send(JSON.stringify({"status": 200, "error": null, "response": value}));
            }
        });
});

我的看跌期权请求不起作用:

router.put('/',  function(req, res) {
   const userId = req.body.userId
   const name = req.body.username
   const address = req.body.address
   const phone = req.body.phone
   const values = [name, address, phone, userId]
   console.log(req.body);
   const sql = "UPDATE userInfo set username =?, address = ?, phone = ?  WHERE userId = ?";
   res.locals.connection.query(sql, values, function (error, results, fields) {
            if(error){
                res.send(JSON.stringify({"status": 500, "error": error, "response": null}));
            } else {
                const value = {"status":"success", "userId": results.insertId}
                res.send(JSON.stringify({"status": 200, "error": null, "response": value}));
            }
        });
});

请建议我,这是什么问题,我怎么能得到身体。

1 个答案:

答案 0 :(得分:0)

对于更新功能,当我使用API​​时,我也面临同样的问题。继续挠头寻找问题两天。最终,我使用了post函数,并且对我有用。

只需使用router.post代替router.put