我寫了Express中間件從請求中檢索原始主體,並在body-parser中間件之前設置它。編寫express express中間件,在body-parser之前獲取原始請求體
我定製的中間件呼籲req.setEncoding('utf8')
,但是這將導致以下機身解析器錯誤:
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);
});
有沒有辦法來未設置編碼?還有另一種方法可以退出原始身體,但仍然使用身體分析器後?
bodyParser,然後再使用中間件? – nicovank
你在'res.sendStatu(200);'中也有一個錯字。 – doublesharp
你確定你需要設置編碼嗎? – doublesharp