3 回答

TA貢獻(xiàn)1825條經(jīng)驗 獲得超4個贊
使用bodyParser中的verify回調(diào),我得到了一個與bodyParser配合良好的解決方案。在這段代碼中,我正在使用它來獲取內(nèi)容的sha1并獲取原始內(nèi)容。
app.use(bodyParser.json({
verify: function(req, res, buf, encoding) {
// sha1 content
var hash = crypto.createHash('sha1');
hash.update(buf);
req.hasha = hash.digest('hex');
console.log("hash", req.hasha);
// get rawBody
req.rawBody = buf.toString();
console.log("rawBody", req.rawBody);
}
}));
我是Node.js和express.js的新手(從昨天開始,從字面上看?。?,所以我想聽聽對此解決方案的評論

TA貢獻(xiàn)2041條經(jīng)驗 獲得超4個贊
請謹(jǐn)慎處理其他答案,因為如果您還希望支持json,urlencoded等,它們將無法在bodyParser上正常播放。要使其與bodyParser一起使用,應(yīng)將處理程序設(shè)置為僅在Content-Type標(biāo)頭上注冊就像bodyParser本身一樣關(guān)心。
為了得到一個請求的原始主體內(nèi)容Content-Type: "text/plain"到req.rawBody你可以這樣做:
app.use(function(req, res, next) {
var contentType = req.headers['content-type'] || ''
, mime = contentType.split(';')[0];
if (mime != 'text/plain') {
return next();
}
var data = '';
req.setEncoding('utf8');
req.on('data', function(chunk) {
data += chunk;
});
req.on('end', function() {
req.rawBody = data;
next();
});
});
- 3 回答
- 0 關(guān)注
- 1137 瀏覽
添加回答
舉報