表达js req.body未定义

时间:2013-07-25 14:38:42

标签: node.js express

我在使用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格式,我检查了正确的请求标题。

2 个答案:

答案 0 :(得分:1)

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

如果您使用的是Express 2.x,那么@DavidKrisch的{​​{3}}就足够了(复制如下)

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

答案 1 :(得分:0)

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

来自:http://expressjs.com/api.html#middleware

  

<强> bodyParser()

     

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

相关问题