简体   繁体   中英

Node JS + Put request does not has body

I start exploring NodeJS and working on API's sample. I am able to get req.body in post request and it is working fine but when i create function to put, my req.body come empty like {} . My code as below:

Post request which is working:

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

My put request which is not working:

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

Please suggest me, what is wrong in that and how can i get req.body.

For update functionality, I also faced the same problem when I was working on APIs. Kept scratching my head to find the problem for two days. Eventually, I used the post function and it worked for me.

Just use router.post instead of router.put .

Verify bodyParser in your app.js file. If it contains only "bodyParser.json":

app.use(bodyParser.json());

you'll get an empty body unless you use "application/json" content type. For: "text/plain" use:

app.use(bodyParser.text());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM