我该如何访问由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);
应该可以使用类似这样的代码:
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);
bodyParser()
中间件曾经有 .rawBody
,但已被移除:https://github.com/senchalabs/connect/commit/c3170eee8cd60c92bcccca6054c1ebbb93a1a821#diff-0 - stewebodyParser.text()
中间件可以将文本主体放入req.body
中。app.use(bodyParser.text({type: '*/*'}));
如果您想将文本正文的处理限制在特定路由或文章内容类型上,也可以这样做。
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}));
如果您需要一个原始的Buffer
,您可以使用bodyParse.raw()
。app.use(bodyParser.raw({type: '*/*'}));
注意:本答案是在 node v0.12.7、express 4.13.2 和 body-parser 1.13.3 版本进行测试的。app.use(bodyParser.text({ type: '*/xml' }));
这样可以很好地填充我的req.body。 - romiemapp.use(bodyParser.raw({type: '*/*'}));
如果您想要二进制数据作为缓冲区。 - Bernardo Ramostext()
,但你提到要使用 raw()
。 - Matt Brownetext()
还是 raw()
? - koronaraw()
返回一个缓冲区,text()
解析为文本并返回一个字符串。对于这个特定的问题,他们想要使用 text()
,我会更新答案。 - Aaron Silvermanapp.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());
默认情况下,express
不会缓存数据,除非您添加中间件来执行此操作。简单的解决方案是遵循下面@Stewe答案中的示例,手动合并所有数据,例如:
var concat = require('concat-stream');
app.use(function(req, res, next){
req.pipe(concat(function(data){
req.body = data;
next();
}));
});
这样做的缺点是您现在将所有POST请求的内容移动到RAM中作为一个连续的块,这可能并不必要。另一个值得考虑的选项取决于您需要处理多少数据的post请求体,可以考虑将数据作为流进行处理。
例如,对于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();
});
});
var concat = require('concat-stream');
部分? - loganfsmythapp.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;
}
}));
看起来Express的bodyParser只会解析传入数据,如果content-type
被设置成以下任意一种情况:
application/x-www-form-urlencoded
application/json
multipart/form-data
在其他所有情况下,它甚至都不会读取数据。
你可以将express/node_modules/connect/lib/middleware/bodyParser.js的第92行更改为:
} else {
next();
}
致:
} else {
var data='';
req.setEncoding('utf8');
req.on('data', function(chunk) {
data += chunk;
});
req.on('end', function() {
req.rawBody = data;
next();
});
}
然后,在你的代码中读取req.rawBody
。
如果您想将正文内容作为缓冲区:
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();
});
}
或者
var rawParser = bodyParser.raw({type: '*/*'});
然后:
app.put('/:name', rawParser, function(req, res) {
console.log('isBuffer:', Buffer.isBuffer(req.body));
})
对于所有的路由:
app.use(bodyParser.raw({type: '*/*'}));
看起来现在这变得容易多了!
现在,body-parser模块可以解析原始数据和文本数据,这使得任务成为一个一行代码:
app.use(bodyParser.text({type: 'text/plain'}))
或者
app.use(bodyParser.raw({type: 'application/binary'}))
这两行代码只是填充了body
属性,因此可以使用res.body
获取文本。
bodyParser.text()
将给你UTF8字符串,而bodyParser.raw()
将给你原始数据。
这是纯文本数据的完整代码:
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()
})
完整文档请参阅: https://www.npmjs.com/package/body-parser
我使用了express 4.16和body-parser 1.18。
所有的答案都已过时,如果任何人仍在苦苦挣扎,那么Express内置了中间件Express raw middleware。
这个中间件在 Express v4.16.0 及以上版本中可用。 这是一个内置于 Express 中的中间件函数。它解析带有 JSON 负载的传入请求,并基于 body-parser 实现。
var express = require("express");
var app = express();
app.use(express.raw({ type: "*/*" }))
app.post("/", (req, res) => {
// req.body = JSON.parse(req.body); // To parse JSON if needed (in-case)
console.log(req.body);
res.end();
});
app.listen(3000, (err) => {
if(!err) console.log("App running!!")
});
app.use (function(req, res, next) {
req.rawBody = '';
req.setEncoding('utf8');
req.on('data', function(chunk) { req.rawBody += chunk });
});
next();
了。在加上这行代码后,它对我有效了。 - Maxime Fafard
require('express')
即可。它会自动找到该模块。 - loganfsmyth