[Fixed] Nodejs Express router middleware for all methods except get


Is there a way to exclude a specific method (say GET) when creating a middleware for route methods that share part of the path?

For example, I have a lot of routes of the form /api/item/*. I want to have something like this to check for bad data

router.all('/api/item/*', (req, res, next) => {
  const { itemId } = req.body;
  if (!itemId) return res.sendStatus(404);

  /* rest of logic here */

But obviously I don’t want GET to also go through this logic as it will have no req.body.

Any thoughts?


As posted in comments above one solution is if (req.method === 'GET') return next();

Another I thought of shortly after (though, not as elegant) is to order my route declarations as such:


Thus only applying the data-checking logic to non-GET requests.

Leave a Reply

(*) Required, Your email will not be published