如何在Express中强制parsing请求主体而不是json?

我正在使用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 }); 

我检查了请求标题和内容types丢失。 即使“内容types”是“文本/纯文本”它似乎parsing为JSON。 有反正告诉中间件总是parsing为纯文本string而不是json的身体? 早期版本的req曾经有req.rawBody ,可以解决这个问题,但现在已经req.rawBody了。 在Express中强制parsing主体为纯文本/string的最简单方法是什么?

如果删除使用bodyParser()中间件,则应该是文本。 您可以查看bodyParser文档以获取更多信息: http : //www.senchalabs.org/connect/middleware-bodyParser.html

删除这一行:

 app.use(express.bodyParser()); 

编辑:

看起来你是对的。 同时您可以创build自己的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的文本parsing器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。 将types选项更改为包含*/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:"*/*"})); 

你可以在这里find文档

您可以使用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); })