我编写了一个 Express 中间件,用于从请求中提取原始正文,并在 body-parser 中间件之前设置它。
我的自定义中间件调用
我的自定义中间件调用
req.setEncoding('utf8')
,但这会导致以下 body-parser 错误:
这是我的代码:Error: stream encoding should not be set
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之后?
res.sendStatu(200);
也有打字错误。 - doublesharpsetEncoding()
,我之前以为必须这样做,因为没有它,应用程序会挂起。现在我明白了,任何试图第二次读取正文的人都会挂起,这种情况下就是 body-parser。 - kiewicnext()
。试着只设置事件处理程序,然后在最后调用next()
,不要在处理程序中调用。 - doublesharpmyMiddleware
中的函数从未被调用,因此next
也没有被调用。 - doublesharp