Node.js服务器:从POST请求获取正文 [英] Node.js server: get body from POST request

查看:87
本文介绍了Node.js服务器:从POST请求获取正文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经用node.js和express.js创建了一个服务器,但是如果我发送POST请求并尝试检查主体,它总是表示主体为空.这是我的代码:

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:

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

如果我现在在www.hurl.it上发出POST请求,并添加带有"Test"之类的文本,它会给我响应"Error",但它应该给我响应"Success",因为正文不为空.

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.

如果我将"body-parser"模块添加到我的应用中,如下所示:

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

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

即使我让身体空着,它也会给我成功".如果我返回req.body,则响应为:{},如果添加一个主体,则它也为{}

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 {}

有人知道怎么了吗?

推荐答案

我认为它总是会遇到错误情况. 试试这个:

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

这篇关于Node.js服务器:从POST请求获取正文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆