Node.js server: get body from POST request

限于喜欢 提交于 2019-12-08 10:45:09

问题


I have created a server with node.js and express.js but if I send a POST request and try to check the body, it always says the body is empty. Here is my code:

app.js:

var express = require('express');

var app = express();

app.set('port', process.env.PORT || 61000);

require('./routes/routes.js')(app);

var server = app.listen(app.get('port'), function () {

    var port = server.address().port;

    console.log('Server runs on port %s', port);

});

routes/routes.js:

module.exports = function(app) {        

     app.get('/', function(req, res) { 
          res.status(200).json({"response": "Hello!"});    
     });     

     app.post('/', function (req, res) {

         if (req.body != null) {
             res.status(200).json("Success");
         }

         res.status(200).json("Error");
     });
};

If I do a POST request now on www.hurl.it and add a body with a text like "Test", it gives me the response "Error", but it should give me the response "Success", because the body is not null.

And if I add the "body-parser" module to my app like this:

var bodyParser = require('body-parser');
...
app.use(bodyParser.json());

it gives me "Success" even if I let the body empty. If I return req.body the response is: {} and if I add a body it is also {}

Someone know what is wrong?


回答1:


I thinks its always hitting the error case. Try this:

if (req.body != null) {
  res.status(200).json("Success");
} else {
  res.status(200).json("Error");
}


来源:https://stackoverflow.com/questions/40306797/node-js-server-get-body-from-post-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!