1

Consider the following Express code:

router.get('/v1/api/book/:id', function (req, res) {
  if (!req.params.id)
    res.status(401).send('Missing book id');
  res.status(200).send('Book found!');
});
  • By invoking http://myserver/v1/api/book/12345689, the application returns 200 > Book found!, as expected.
  • However, http://myserver/v1/api/book returns 404 > Cannot GET /v1/api/book, instead of 401 > Missing book id.

Could you please explain me why and how could I fix this behaviour?

SubZeno
  • 341
  • 3
  • 15

2 Answers2

1

You have to declare the id path parameter optional, otherwise the route won't match (see http://expressjs.com/en/guide/routing.html#route-parameters for more information).

You can do it like this:

router.get('/v1/api/book/:id?', function (req, res) { ... }
eol
  • 23,236
  • 5
  • 46
  • 64
1

Your route /v1/api/book/:id expects an id . You have posted without passing an id that is not decleared in any route in the application. if you need to pass an id as optional parameter then your route should be look like v1/api/book/:id?

And,I recommend returning proper status code when dealing with api. You should update your status code 401 to 404 if parameter has no id or there is no book with the id. 401 status code stands for unauthorized errors.

router.get('/v1/api/book/:id?', function (req, res) {
  //if parameter has no id passed in send 404 response with message
  //if paraneter has id, search for book with that id . 
  //if any book is found, then send response 200 with message else send response 404 with message.
});
Nayeem Azad
  • 657
  • 5
  • 20