node.js Expressjs 原始体
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9920208/
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
Expressjs raw body
提问by Andrey Kon
How can I access raw body of request object given to me by expressjs?
如何访问 expressjs 给我的请求对象的原始主体?
var express = require('./node_modules/express');
var app = express.createServer();
app.post('/', function(req, res)
{
console.log(req.body); //says 'undefined'
});
app.listen(80);
采纳答案by loganfsmyth
Default expressdoes not buffer data unless you add middleware to do so. The simple solution is to follow the example in @Stewe's answer below, which would just concatenate all of the data yourself. e.g.
express除非您添加中间件,否则默认不会缓冲数据。简单的解决方案是按照下面@Stewe 的答案中的示例进行操作,它只会自己连接所有数据。例如
var concat = require('concat-stream');
app.use(function(req, res, next){
req.pipe(concat(function(data){
req.body = data;
next();
}));
});
The downside of this is that you have now moved all of the POST body content into RAM as a contiguous chunk, which may not be necessary. The other option, which is worth considering but depends on how much data you need to process in the post body, would be to process the data as a stream instead.
这样做的缺点是您现在已经将所有 POST 正文内容作为一个连续的块移动到 RAM 中,这可能不是必需的。另一种值得考虑但取决于您需要在帖子正文中处理多少数据的选项是将数据作为流处理。
For example, with XML you could use an XML parser that supports parsing XML as it comes in as chunks. One such parser would be XML Stream. You do something like this:
例如,对于 XML,您可以使用 XML 解析器,该解析器支持解析以块形式出现的 XML。XML Stream就是这样一种解析器。你做这样的事情:
var XmlStream = require('xml-stream');
app.post('/', function(req, res) {
req.setEncoding('utf8');
var xml = new XmlStream(req);
xml.on('updateElement: sometag', function(element) {
// DO some processing on the tag
});
xml.on('end', function() {
res.end();
});
});
回答by stewe
Something like this should work:
这样的事情应该工作:
var express = require('./node_modules/express');
var app = express.createServer();
app.use (function(req, res, next) {
var data='';
req.setEncoding('utf8');
req.on('data', function(chunk) {
data += chunk;
});
req.on('end', function() {
req.body = data;
next();
});
});
app.post('/', function(req, res)
{
console.log(req.body);
});
app.listen(80);
回答by Zugwalt
Using the bodyParser.text()middleware will put the text body in req.body.
使用bodyParser.text()中间件会将文本正文放入req.body.
app.use(bodyParser.text({type: '*/*'}));
If you want to limit processing the text body to certain routes or post content types, you can do that too.
如果您想将文本正文处理限制为某些路线或发布内容类型,您也可以这样做。
app.use('/routes/to/save/text/body/*', bodyParser.text({type: 'text/plain'})); //this type is actually the default
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
If you want a raw Buffer, you can use bodyParse.raw().
如果你想要一个原始的Buffer,你可以使用bodyParse.raw().
app.use(bodyParser.raw({type: '*/*'}));
Note: this answer was tested against node v0.12.7, express 4.13.2, and body-parser 1.13.3.
注意:此答案针对节点 v0.12.7、express 4.13.2 和 body-parser 1.13.3 进行了测试。
回答by Ben Sinclair
Put the following middleware before bodyParser middleware. It'll collect raw body data in request.rawBody and won't interfere with bodyParser.
将以下中间件放在 bodyParser 中间件之前。它将在 request.rawBody 中收集原始正文数据,并且不会干扰 bodyParser。
app.use(function(req, res, next) {
var data = '';
req.setEncoding('utf8');
req.on('data', function(chunk) {
data += chunk;
});
req.on('end', function() {
req.rawBody = data;
next();
});
});
app.use(express.bodyParser());
回答by poordeveloper
app.use(bodyParser.json({
verify: function (req, res, buf, encoding) {
req.rawBody = buf;
}
}));
app.use(bodyParser.urlencoded({
extended: false,
verify: function (req, res, buf, encoding) {
req.rawBody = buf;
}
}));
回答by Tarandeep Gill
So, it seems like Express's bodyParser only parses the incoming data, if the content-typeis set to either of the following:
因此,如果content-type设置为以下任一项,Express 的 bodyParser 似乎只解析传入的数据:
application/x-www-form-urlencodedapplication/jsonmultipart/form-data
application/x-www-form-urlencodedapplication/jsonmultipart/form-data
In all other cases, it does not even bother reading the data.
在所有其他情况下,它甚至不会打扰读取数据。
You can change line no. 92 of express/node_modules/connect/lib/middleware/bodyParser.js from
您可以更改行号。来自 express/node_modules/connect/lib/middleware/bodyParser.js 的 92 个
} else {
next();
}
To:
到:
} else {
var data='';
req.setEncoding('utf8');
req.on('data', function(chunk) {
data += chunk;
});
req.on('end', function() {
req.rawBody = data;
next();
});
}
And then, read req.rawBodyfrom your code.
然后,阅读req.rawBody您的代码。
回答by Bernardo Ramos
If you want the body as a buffer:
如果您希望将正文作为缓冲区:
var rawParser = function(req, res, next) {
var chunks = [];
req.on('data', function(chunk) {
chunks.push(chunk)
});
req.on('end', function() {
req.body = Buffer.concat(chunks);
next();
});
}
or
或者
var rawParser = bodyParser.raw({type: '*/*'});
and then:
进而:
app.put('/:name', rawParser, function(req, res) {
console.log('isBuffer:', Buffer.isBuffer(req.body));
})
or for all routes:
或对于所有路线:
app.use(bodyParser.raw({type: '*/*'}));
回答by TechplexEngineer
If you are having trouble with the above solutions interfering with normal post requests, something like this might help:
如果您在上述解决方案干扰正常发布请求时遇到问题,这样的操作可能会有所帮助:
app.use (function(req, res, next) {
req.rawBody = '';
req.setEncoding('utf8');
req.on('data', function(chunk) { req.rawBody += chunk });
});
More info & source: https://github.com/visionmedia/express/issues/897#issuecomment-3314823
更多信息和来源:https: //github.com/visionmedia/express/issues/897#issuecomment-3314823
回答by nortron
BE CAREFUL with those other answers as they will not play properly with bodyParser if you're looking to also support json, urlencoded, etc. To get it to work with bodyParser you should condition your handler to only register on the Content-Typeheader(s) you care about, just like bodyParser itself does.
请注意其他答案,因为如果您还希望支持 json、urlencoded 等,它们将无法与 bodyParser 一起正常播放。要使其与 bodyParser 一起使用,您应该将处理程序设置为仅在您的Content-Type标头上注册关心,就像 bodyParser 本身一样。
To get the raw body content of a request with Content-Type: "text/xml"into req.rawBodyyou can do:
为了得到一个请求的原始主体内容Content-Type: "text/xml"到req.rawBody你可以这样做:
app.use(function(req, res, next) {
var contentType = req.headers['content-type'] || ''
, mime = contentType.split(';')[0];
if (mime != 'text/xml') {
return next();
}
var data = '';
req.setEncoding('utf8');
req.on('data', function(chunk) {
data += chunk;
});
req.on('end', function() {
req.rawBody = data;
next();
});
});
回答by JCH2k
It seems this has become a lot easier now!
现在这似乎变得容易了很多!
The body-parser module is able to parse raw and text data now, which makes the task a one-liner:
body-parser 模块现在能够解析原始数据和文本数据,这使得任务成为一个单线任务:
app.use(bodyParser.text({type: 'text/plain'}))
OR
或者
app.use(bodyParser.raw({type: 'application/binary'}))
Both lines simply fill the bodyproperty, so get the text with res.body.
bodyParser.text()will give you the UTF8 string while bodyParser.raw()will give you the raw data.
这两行都只是简单地填充了body属性,所以用res.body.
bodyParser.text()会给你 UTF8 字符串,同时bodyParser.raw()会给你原始数据。
This is the full code for text/plain data:
这是文本/纯数据的完整代码:
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
app.use(bodyParser.text({type: 'text/plain'}))
app.post('/', function (req, res, next) {
console.log('body:\n' + req.body)
res.json({msg: 'success!'})
next()
})
See here for the full documentation: https://www.npmjs.com/package/body-parser
有关完整文档,请参见此处:https: //www.npmjs.com/package/body-parser
I used express 4.16 and body-parser 1.18
我使用了 express 4.16 和 body-parser 1.18

