Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

expressJS: Limit acceptable content-types

I have a expressJS API. In POST routes, I only accept two types of headers:

application/x-www-form-urlencoded

application/json

Is there a way that I can express to enforce to only accept the two headers and reject any other POST request and respond with some kind of 400 error?

like image 899
samol Avatar asked Nov 07 '25 11:11

samol


1 Answers

You could use a simple middleware like this on a per-route basis or for all routes:

var RE_CONTYPE = /^application\/(?:x-www-form-urlencoded|json)(?:[\s;]|$)/i;
app.use(function(req, res, next) {
  if (req.method === 'POST' && !RE_CONTYPE.test(req.headers['content-type']))
    return res.send(415);
  next();
});
like image 63
mscdex Avatar answered Nov 10 '25 04:11

mscdex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!