An SO User
An SO User

Reputation: 24998

ExpressJS limiting body size with custom message

In my ExpressJS code, I am limiting the body size as follows:

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

When the body size exceeds the limit, I want to send back a custom JSON response message. How can I do that?

Upvotes: 0

Views: 993

Answers (1)

vmkcom
vmkcom

Reputation: 1668

add error handler after your bodyparser middleware. Response status will be 413 - Entity Too Large

https://github.com/expressjs/body-parser#errors

  app.use(function(err, req, res, next) {
    console.log(err);
    if (err.statusCode === '413')
      return res.send('NOT OK, ENTITY TOO LARGE');
  });

Do not forget to check other errors, not only body-parser related

Upvotes: 2

Related Questions