【发布时间】:2016-11-16 17:00:50
【问题描述】:
我编写了一个 Express 中间件来从请求中检索原始正文,并将其设置在 body-parser 中间件之前。
我的自定义中间件正在调用req.setEncoding('utf8'),但这会导致以下正文解析器错误:
错误:不应设置流编码
at readStream (/node_modules/body-parser/node_modules/raw-body/index.js:211:17) at getRawBody (/node_modules/body-parser/node_modules/raw-body/index.js:106:12) at read (/node_modules/body-parser/lib/read.js:76:3) at jsonParser (/node_modules/body-parser/lib/types/json.js:127:5)
这是我的代码:
var express = require('express');
var bodyParser = require('body-parser')
function myMiddleware() {
return function(req, res, next) {
req.rawBody = '';
req.setEncoding('utf8');
req.on('data', function(chunk) {
req.rawBody += chunk;
});
req.on('end', function() {
next();
});
}
}
var app = express();
app.use(myMiddleware());
app.use(bodyParser.json());
var listener = app.listen(3000, function() {
});
app.get('/webhook/', function (req, res) {
res.sendStatus(200);
});
有没有办法取消设置编码?是否有另一种方法来检索原始正文,但在它之后仍然使用 body-parser?
【问题讨论】:
-
在 bodyParser 之后使用你的中间件?
-
您在
res.sendStatu(200);中也有错字。 -
您确定需要设置编码吗?
-
@doublesharp 错字已修复,谢谢!
-
@nicovank 如果我更改中间件顺序,我的自定义中间件会挂起。我想这是因为流已经被消耗了。我正在调查它可能是什么。
标签: node.js body-parser