如果去掉bodyParser()
中间件的使用,应该是文本。您可以查看bodyParser
文档以获取更多信息:http ://www.senchalabs.org/connect/middleware-bodyParser.html
删除这一行:
app.use(express.bodyParser());
编辑:
看起来你是对的。同时,您可以创建自己的rawBody
中间件。但是,您仍然需要禁用bodyParser()
. 注意:req.body
仍将是undefined
.
这是一个演示:
应用程序.js
var express = require('express')
, http = require('http')
, path = require('path')
, util = require('util');
var app = express();
function rawBody(req, res, next) {
req.setEncoding('utf8');
req.rawBody = '';
req.on('data', function(chunk) {
req.rawBody += chunk;
});
req.on('end', function(){
next();
});
}
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.use(rawBody);
//app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
});
app.post('/test', function(req, res) {
console.log(req.is('text/*'));
console.log(req.is('json'));
console.log('RB: ' + req.rawBody);
console.log('B: ' + JSON.stringify(req.body));
res.send('got it');
});
http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
测试.js
var request = require('request');
request({
method: 'POST',
uri: 'http://localhost:3000/test',
body: {'msg': 'secret'},
json: true
}, function (error, response, body) {
console.log('code: '+ response.statusCode);
console.log(body);
})
希望这可以帮助。