node.js 如何强制将请求正文解析为纯文本而不是 Express 中的 json?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12345166/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:16:57  来源:igfitidea点击:

How to force parse request body as plain text instead of json in Express?

jsonnode.jsexpresscontent-typeconnect

提问by pathikrit

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

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

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 reqused to have req.rawBodythat 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?

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

采纳答案by JP Richardson

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

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

Remove this line:

删除这一行:

app.use(express.bodyParser());

EDIT:

编辑:

Looks like you're right. You can create your own rawBodymiddleware in the meantime. However, you still need to disable the bodyParser(). Note: req.bodywill still be undefined.

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

Here is a demo:

这是一个演示:

app.js

应用程序.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

测试.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);
})

Hope this helps.

希望这可以帮助。

回答by Nacho

In express 4.x you can use the text parser from bodyParser https://www.npmjs.org/package/body-parser

在 express 4.x 中,您可以使用 bodyParser https://www.npmjs.org/package/body-parser 中的文本解析器

just add in app.js

只需添加 app.js

app.use(bodyParser.text());

Also in the desired route

也在想要的路线上

router.all('/',function(req,res){
    console.log(req.body);

})

回答by Raghu

By default bodyParser.text()handles only text/plain. Change the type options to include */jsonor */*.

默认情况下bodyParser.text()仅处理文本/纯文本。将类型选项更改为 include*/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:"*/*"}));

You can find the docs here

你可以在这里找到文档

回答by dimpiax

Express understands by content-type how to decode a body. It must have specific decoders in middlewares, which is embedded into the library from 4.x:

Express 通过内容类型了解如何解码正文。它必须在中间件中有特定的解码器,从4.x嵌入到库中:

app.use(express.text())
app.use(express.json())

回答by Carlos

You can use the plainTextParser (https://www.npmjs.com/package/plaintextparser) middleware..

您可以使用 plainTextParser ( https://www.npmjs.com/package/plaintextparser) 中间件..

let plainTextParser = require('plainTextParser');
app.use(plainTextParser());

or

或者

app.post(YOUR_ROUTE, plainTextParser, function(req, res) {             
  let text = req.text;

  //DO SOMETHING....
}); 

回答by vpmayer

I did it:

我做到了:

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

})

回答by crazyDiamond

Make sure the version of express and bodyParser has been upgraded to the appropriate versions. Express ?4.x and bodyParser ?1.18.x. That should do it. With that in place the following should work

确保 express 和 bodyParser 的版本已经升级到合适的版本。Express ?4.x 和 bodyParser ?1.18.x。那应该这样做。有了这个,以下应该工作

app.use(bodyParser.text());

app.use(bodyParser.text());

回答by Leo Bastin

Two important things to achieve this.

实现这一目标的两件重要事情。

  1. You need to add the text middleware in order to process text in the body
  2. You need to set the content type by adding the right header "Content-type: text/plain" in the request
  1. 您需要添加文本中间件才能处理正文中的文本
  2. 您需要通过在请求中添加正确的标头“Content-type: text/plain”来设置内容类型

Here is the sample code for both.

这是两者的示例代码。

const express = require('express');
const app = express();
const bodyParser = require('body-parser')
//This is the needed text parser middleware 
app.use(bodyParser.text()); 

app.post('/api/health/', (req, res) => {
    res.send(req.body);
});

const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Listening on ${port} ${new Date(Date.now())}`));

Save this as index.js.

将其另存为 index.js。

Install dependencies.

安装依赖项。

npm i -S express 
npm i -S body-parser

Run it.

运行。

node index.js

Now send a request to it.

现在向它发送请求。

curl -s -XPOST -H "Content-type: text/plain" -d 'Any text or  json or whatever {"key":value}' 'localhost:3000/api/health'

You should be able to see it sending back whatever you posted.

您应该能够看到它发送回您发布的任何内容。