user3677331
user3677331

Reputation: 698

Express route wrong match

I've read up other questions on people's routes mismatching and then ordering the routes solving the problem. I've got this problem where my URL route is being treated as a parameter and then express mismatches and leads to the wrong route. e.g. here are the two routes:

app.get('/byASIN/LowPrice/:asin/:price',function(req,res){});

and

app.get('/byASIN/:asin/:price', function(req, res) {});

Now all works fine but as soon as I take any param out of the first route it matches the route given below which is not what I want. If I hit /byASIN/LowPrice/:asin/:price everything works fine but as soon as I hit /byASIN/LowPrice/:asin it matches byASIN/:asin/:price and hence calls the wrong function and crashes my server. I would like to have them match explicitly and if /byASIN/LowPrice/:asin is called, respond with some warning e.g. you're calling with one less argument. What am I missing here?

Upvotes: 3

Views: 2756

Answers (3)

Anthony C
Anthony C

Reputation: 2157

Express matches the route by the order you insert them. If you have the loosely routes defined first, then express will use that one as the match first. An extreme example would be

app.get('*', function(req, res) {});

If this was defined as the first route, then no other route will be called (if without calling next()).

If you want express to always use the strict one first, then you will need to change the order of your routes by having the strict ones defined before the loosely ones.

It'd be nice if express support priority in the route, which could be a good solution for your problem, but until then, unfortunately, this can be fixed by ordering only :(

Upvotes: 0

BrTkCa
BrTkCa

Reputation: 4783

Try to define a route for /byASIN/LowPrice/:asin/:price to handle, then use a wildcard to handle everything else.

app.get('/byASIN/LowPrice/:asin/:price',function(req,res){});

app.get('*',function(req,res){});

Upvotes: 0

Nick D
Nick D

Reputation: 1493

By default express Url parameters are not optinial, this is why

app.get('/byASIN/LowPrice/:asin/:price',function(req,res){});

does not match /byASIN/LowPrice/:asin, because the second parameter is missing.

However you can make a parameter optional by adding a ? to it:

app.get('/byASIN/LowPrice/:asin/:price?',function(req,res){});

this should solve your problem.

Upvotes: 3

Related Questions