如何在Express中强制解析请求体作为纯文本而不是json?

问题描述 投票:32回答:6

我正在使用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中强制解析正文作为纯文本/字符串的最简单方法?

json node.js express content-type connect
6个回答
22
投票

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

删除此行:

app.use(express.bodyParser());

EDIT:

看起来你是对的。您可以在此期间创建自己的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);
})

希望这可以帮助。


25
投票

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

})

24
投票

默认情况下,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


3
投票

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

1
投票

我做的:

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

})

0
投票

确保express和bodyParser的版本已升级到适当的版本。表达〜4.x和bodyParser~1.18.x。应该这样做。有了这些,以下应该有效

app.use(bodyParser.text());

© www.soinside.com 2019 - 2024. All rights reserved.