如何强制将请求正文解析为纯文本而不是 Express 中的 json? [英] How to force parse request body as plain text instead of json in Express?

查看:27
本文介绍了如何强制将请求正文解析为纯文本而不是 Express 中的 json?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 nodejs + Express (v3),如下所示:

I am using nodejs + Express (v3) like this:

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

我检查了请求标头,但缺少内容类型.即使内容类型"是文本/纯文本",它似乎也被解析为 JSON.无论如何要告诉中间件始终将正文解析为纯文本字符串而不是 json?req 的早期版本曾经有 req.rawBody 可以解决这个问题,但现在它不再了.在 Express 中强制将正文解析为纯文本/字符串的最简单方法是什么?

I checked the request headers and the content-type is missing. Even if "Content-Type" is "text/plain" it is parsing as a JSON it seems. Is there anyway to tell the middleware to always parse the body as a plain text string instead of json? Earlier versions of req used to have req.rawBody that would get around this issue but now it does not anymore. What is the easiest way to force parse body as plain text/string in Express?

推荐答案

如果去掉了 bodyParser() 中间件的使用,它应该是文本.您可以查看 bodyParser 文档了解更多信息:http://www.senchalabs.org/connect/middleware-bodyParser.html

If you remove the use of the bodyParser() middleware, it should be text. You can view the bodyParser docs for more info: http://www.senchalabs.org/connect/middleware-bodyParser.html

删除这一行:

app.use(express.bodyParser());

看来你是对的.在此期间,您可以创建自己的 rawBody 中间件.但是,您仍然需要禁用 bodyParser().注意:req.body 仍然是 undefined.

Looks like you're right. You can create your own rawBody middleware in the meantime. However, you still need to disable the bodyParser(). Note: req.body will still be 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 中的 json?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆