Jose Arrillaga
Jose Arrillaga

Reputation: 41

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 */
  next()
});

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

Any thoughts?

Upvotes: 0

Views: 916

Answers (1)

Jose Arrillaga
Jose Arrillaga

Reputation: 41

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:

router.get(...);
router.all(...);

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

Upvotes: 1

Related Questions