Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 381
user3677331 Avatar asked Apr 24 '26 10:04

user3677331


1 Answers

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.

like image 86
Nick D Avatar answered Apr 26 '26 01:04

Nick D



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!