我正在使用nodejs + Express(v3),如下所示:
app.use(express.bodyParser());
app.route('/some/route', function(req, res) {
var text = req.body; // I expect text to be a string but it is a JSON
});
我检查了请求标头,但缺少内容类型。即使“Content-Type”是“text / plain”,它也可以解析为JSON。反正有没有告诉中间件总是将正文解析为纯文本字符串而不是json?早期版本的req
曾经有req.rawBody
可以解决这个问题,但现在它不再存在了。什么是在Express中强制解析正文作为纯文本/字符串的最简单方法?
如果你删除使用bodyParser()
中间件,它应该是文本。您可以查看bodyParser
文档以获取更多信息:http://www.senchalabs.org/connect/middleware-bodyParser.html
删除此行:
app.use(express.bodyParser());
看起来你是对的。您可以在此期间创建自己的rawBody
中间件。但是,您仍然需要禁用bodyParser()
。注意:req.body
仍然是undefined
。
这是一个演示:
app.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'));
});
test.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);
})
希望这可以帮助。
在express 4.x中,您可以使用bodyParser https://www.npmjs.org/package/body-parser中的文本解析器
只需添加app.js
app.use(bodyParser.text());
也在所需的路线
router.all('/',function(req,res){
console.log(req.body);
})
默认情况下,bodyParser.text()
只处理text / plain。更改类型选项以包括*/json
或*/*
。
app.use('/some/route', bodyParser.text({type: '*/*'}), function(req, res) {
var text = req.body; // I expect text to be a string but it is a JSON
});
//or more generally:
app.use(bodyParser.text({type:"*/*"}));
你可以找到文件here
您可以使用plainTextParser(https://www.npmjs.com/package/plaintextparser)中间件..
let plainTextParser = require('plainTextParser');
app.use(plainTextParser());
要么
app.post(YOUR_ROUTE, plainTextParser, function(req, res) {
let text = req.text;
//DO SOMETHING....
});
我做的:
router.route('/')
.post(function(req,res){
var chunk = '';
req.on('data', function(data){
chunk += data; // here you get your raw data.
})
req.on('end', function(){
console.log(chunk); //just show in console
})
res.send(null);
})
确保express和bodyParser的版本已升级到适当的版本。表达〜4.x和bodyParser~1.18.x。应该这样做。有了这些,以下应该有效
app.use(bodyParser.text());