ExpressJS用自定义消息限制正文大小

ExpressJS limiting body size with custom message

本文关键字:正文 自定义消息 ExpressJS      更新时间:2023-09-26

在我的ExpressJS代码中,我限制了主体大小如下:

app.use(bodyParser.urlencoded({ 
    limit : "512kb",
    extended: false,
    type : "application/x-www-form-urlencoded"
}));  

当正文大小超过限制时,我想发送回一个自定义JSON响应消息。我该怎么做呢?

在bodyparser中间件之后添加错误处理程序。响应状态将为413 -实体太大

https://github.com/expressjs/body-parser错误
  app.use(function(err, req, res, next) {
    console.log(err);
    if (err.statusCode === '413')
      return res.send('NOT OK, ENTITY TOO LARGE');
  });

不要忘记检查其他错误,不仅仅是body-parser相关的