[英]How to write independent/isolated express middleware with access to raw request body
我正在嘗試編寫一個可以訪問原始請求正文的Express中間件。 所以像這樣的東西(實際上有效並且)將是理想的:
const middleware = [
express.raw({ type: '*/*' }),
(req, res, next) => {
digest(req.body);
next();
},
];
但是,這種方法意味着req.body
現在已經被流式處理/處理,並且現在對於我的中間件之后的任何處理程序或中間件都不可用:
app.post(route, middleware, (req, res) => res.send(req.body)); // returns `{}`
我希望可以將我的中間件與其他正文解析器一起使用。 所以這應該沒問題:
app.use(express.json());
app.post(route, middleware, (req, res) => res.send(req.body)); // should return the JSON body posted not `{}`
還有這個:
app.post(route, middleware, express.json(), (req, res) => res.send(req.body)); // should return the JSON body posted not `{}`
是否有可能:
express.raw({ type: '*/*' })
以外的方式獲取原始主體?如果上述內容不夠清楚,我已將這些片段擴展為此存儲庫中的失敗測試,並希望得到任何幫助或指示。
因此,通過更多的研究(和睡眠) ,我認為我的方法可能是不正確的。
更合適的解決方案是使用相關正文解析器的verify
選項,它使您可以訪問緩沖區:
app.use(express.json({ verify: (req, res, buf, encoding) => digest(buf) || throw 'Invalid Digest' }));
app.post(route, (req, res) => res.send(req.body));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.