简体   繁体   English

Node.js服务器:从POST请求获取正文

[英]Node.js server: get body from POST request

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. 我已经用node.js和express.js创建了一个服务器,但是如果我发送POST请求并尝试检查正文,它总是说正文为空。 Here is my code: 这是我的代码:

app.js: 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: route / 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. 如果我现在在www.hurl.it上发出POST请求,并添加带有“ Test”之类的文本,它会给我响应“ Error”,但它应该给我响应“ Success”,因为该正文不是空值。

And if I add the "body-parser" module to my app like this: 如果我将“ body-parser”模块添加到我的应用中,如下所示:

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 {} 如果返回req.body,则响应为:{};如果添加一个body,则也为{}

Someone know what is wrong? 有人知道怎么了吗?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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