akki_2891
akki_2891

Reputation: 516

ExpressJs : Differentiating between two similar routes

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.

Upvotes: 2

Views: 478

Answers (4)

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123423

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

Upvotes: 2

tpie
tpie

Reputation: 6221

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.

Upvotes: 1

filype
filype

Reputation: 8380

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

Upvotes: 0

Martin Konecny
Martin Konecny

Reputation: 59581

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.

Upvotes: 0

Related Questions