我正在嘗試使用以下方法將有效負載限制為 1kb:
app.use(bodyParser.json({
limit: "1kb" ,
strict:true
}));
它完美地作業,因為它想作業,但唯一的問題是,我得到一個錯誤的
PayloadTooLargeError: request entity too large
at readStream (E:\Work\FIGHTME\V1.0\api\node_modules\raw-body\index.js:155:17)
at getRawBody (E:\Work\FIGHTME\V1.0\api\node_modules\raw-body\index.js:108:12)
at read (E:\Work\FIGHTME\V1.0\api\node_modules\body-parser\lib\read.js:77:3)
at jsonParser (E:\Work\FIGHTME\V1.0\api\node_modules\body-parser\lib\types\json.js:135:5)
at Layer.handle [as handle_request] (E:\Work\FIGHTME\V1.0\api\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (E:\Work\FIGHTME\V1.0\api\node_modules\express\lib\router\index.js:317:13)
at E:\Work\FIGHTME\V1.0\api\node_modules\express\lib\router\index.js:284:7
at Function.process_params (E:\Work\FIGHTME\V1.0\api\node_modules\express\lib\router\index.js:335:12)
at next (E:\Work\FIGHTME\V1.0\api\node_modules\express\lib\router\index.js:275:10)
at expressInit (E:\Work\FIGHTME\V1.0\api\node_modules\express\lib\middleware\init.js:40:5)
有什么方法可以通過回呼或任何方式處理此錯誤,以便我顯示自定義錯誤或發送自定義回應?
uj5u.com熱心網友回復:
你試過這樣嗎
app.use(express.json({limit: '1kb'}));
Express v4.16.0 以后可以將請求正文決議為中間件。
編輯
如果要自定義錯誤訊息,則需要定義錯誤處理程式中間件來執行此操作。像這樣的東西:
// Not tested code.
// Usually added as last middleware
app.use(function (err, req, res, next) {
if(err instanceof PayloadTooLargeError){
//res.status(<your status code>).send(<your response>);
res.status(400).send("Customized Response");
}
else{
next(err);
}
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/380621.html
標籤:javascript 节点.js 表达 正文解析器
下一篇:另一個類中的C 類物件
