1

I've setup middleware to check for the presence of a required parameter in an API call. The problem is, if the parameter is missing my middleware never gets called. I simply get a generic 404 error because the route couldn't be identified. I'm trying to figure out what I'm missing:

routes.js:

router.get('/players/:id/info',
  middleware.params.ensureExist,
  info.index
);

/middleware/params.js:

var ensureExist = function(req, res, next) {
  var id = req.params && req.params.id;
  if (id) {
    return next();
  } else {
    logger.warn('req.params.id required.', { error: 'Missing req.params.id' });
    return res.status(400).send({ error: 'Missing req.params.id' });
  }
};

GET '/players/56/info' produces the expected response. However, GET '/players/info' just gives me a generic 404 instead of the custom error message above.

1 Answer 1

1

The problem is that your middleware will only be called on routes that include the :id param, because you have it mounted on '/players/:id/info'. You'll need to mount it on '/players' in order to match both cases.

Sign up to request clarification or add additional context in comments.

3 Comments

Sorry, that was just a typo on my part. Fixed now.
Oops, that was supposed to be a comment, not an answer! I blame my mobile.
Changed to my actual answer, sorry about that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.