Cyril Gaillard
Cyril Gaillard

Reputation: 909

Express - how to block invalid http methods?

I am getting invalid http methods (see below) which trigger timeout errors from my server as the route is valid. Is there any way to block all invalid requests in Express? I can't find anything on google. Invalid http requests

Upvotes: 3

Views: 949

Answers (1)

King Friday
King Friday

Reputation: 26086

Take a whitelist approach

// before your other code check supported methods
// assuming these ones are, just add/remove ones to customize
if (!/^(GET|PUT|POST|DELETE)$/.test(req.method)) {
  res.status(400).end('bad request');
  return;
}

// your code goes here now

or use middleware if using express

router.use((req, res, next) => {
  if (!/^(GET|PUT|POST|DELETE)$/.test(req.method)) {
    res.status(400).end('bad request');
    return;
  }
  next();
});

In the words of Donald Rumsfeld...

Reports that say that something hasn't happened are always interesting to me, because as we know, there are known knowns; there are things we know we know. We also know there are known unknowns; that is to say we know there are some things we do not know. But there are also unknown unknowns – the ones we don't know we don't know. And if one looks throughout the history of our country and other free countries, it is the latter category that tend to be the difficult ones.

tl;dr Point being, you can only know what you know so use a whitelist.

Upvotes: 2

Related Questions