【问题标题】:express3 js req.body is undefinedexpress3 js req.body 未定义
【发布时间】:2013-07-26 01:49:58
【问题描述】:

我在使用 req.body 时使用 express2.js 我得到未定义或空的 {}:

exports.post = function (req: express3.Request, res: express3.Response) {
    console.log(req.body);    
});

我有以下配置:

app.use(express.bodyParser());
app.use(app.router);

app.post('/getuser', routes.getuserprofile.post);

请求正文是 XML 格式,我检查了正确的请求标头。

【问题讨论】:

  • 为什么参数中有: express3.Request 的东西?

标签: node.js express


【解决方案1】:

我错过了你有 XML 的部分。我猜 req.body 默认不解析。

如果您使用的是 Express 2.x,那么 @DavidKrisch 的 this solution 可能就足够了(复制如下)

// This script requires Express 2.4.2
// It echoes the xml body in the request to the response
//
// Run this script like so:
// curl -v -X POST -H 'Content-Type: application/xml' -d '<hello>world</hello>' http://localhost:3000
var express = require('express'),
    app = express.createServer();

express.bodyParser.parse['application/xml'] = function(data) {
    return data;
};

app.configure(function() {
    app.use(express.bodyParser());
});


app.post('/', function(req, res){
    res.contentType('application/xml');
    res.send(req.body, 200);
});

app.listen(3000);

【讨论】:

    【解决方案2】:

    我不相信express.bodyParser() 支持 XML。它只支持url编码的参数和JSON。

    发件人:http://expressjs.com/api.html#middleware

    bodyParser()

    请求正文解析中间件支持 JSON、urlencoded 和 多部分请求。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-04
      • 2012-02-28
      • 2016-09-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多