2

I have two routes /api/persons/:personId and /api/persons/contact,where :personId is an ObjectId.

When i am hitting api/persons/contactS (with an 'S' character),it is hitting the API code for api/persons/:personId instead of giving 404.

So how can i distinguish between the two routes.I want to restrict my code control upfront where i define my routes before giving the handle to controller.

akki_2891
  • 496
  • 1
  • 5
  • 12

4 Answers4

2

Express depends on path-to-regexp for parsing route paths, which supports specifying custom patterns with placeholders:

app.get('/api/persons/:personId([\\dA-Fa-f]+)', ...);

app.get('/api/persons/contact', ...);

You can also use app.param() to validate personId when it might be used:

app.param('personId', function (req, res, next, id) {
    Persons.findById(id, function (err, person) {
        if (err)
            return next(err);
        if (!person)
            return next('route');

        req.person = person;
        next();
    });
});
Jonathan Lonowski
  • 121,453
  • 34
  • 200
  • 199
1

You need to put some kind of validation on the req, server side. It's doing that because it's thinking you are sending it a personId. I am sure your personId's match a certain format, so add some validation that checks the format of the personId. If it doesn't match, return 404 (or whatever error suits your case)

For example,

var x = req.params.personId
if (x.length !== 10 || x.match(/^[0-9]+$/) != null; ) {
  res.send(404)
}

This would make sure that the personId contains 10 numbers before even accepting it as a personId.

tpie
  • 6,021
  • 3
  • 22
  • 41
0

You need to use regex in your route to distinguish what could be a personId (maybe it's all digits) and what's not.

There's an example of using regex in the route here: https://stackoverflow.com/a/13665354/280842

Community
  • 1
  • 1
filype
  • 8,034
  • 10
  • 40
  • 66
  • I have done that too.. But it does not look the cause. I want to restrict my code control upfront before giving the handle to controller. – akki_2891 Apr 27 '15 at 04:08
0

Why should it give a 404? contactS could be a valid personId.

You will need to add a regular expression to the route

/api/persons/:personId

So that it only matches against valid ObjectId's, and then it will ignore contactS and return a 404.

Martin Konecny
  • 57,827
  • 19
  • 139
  • 159