Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional GET parameter in Express route

The following:

app.get('/foo/start/:start/end/:end', blah.someFunc);

matches

/foo/start/1/end/4

but I want it to also match an optional parameter

/foo/start/1/end/4/optional/7

I've tried this:

app.get('/foo/start/:start/end/:end(/optional/:value)?', blah.someFunc);

but it doesn't match either of the above two examples. I think it's because I'm trying to give it a RegExp when it's expecting something else?

Thanks.

like image 336
ale Avatar asked Sep 04 '13 16:09

ale


2 Answers

Why don't you add another rule before the one you have, like this

app.get('/foo/start/:start/end/:end/optional/:value', blah.someFunc);
app.get('/foo/start/:start/end/:end', blah.someFunc);

It will be used before the one without the optional value.

If you want to use just one line try this:

app.get('/foo/start/:start/end/:end/optional?', blah.someFunc)

see the docs for an example.

like image 87
Alberto Zaccagni Avatar answered Sep 20 '22 11:09

Alberto Zaccagni


If you are using Express 4.x Then I think its better to use array format for route. For example I have route /service which gives all service list and same route when used with id /service/id/:id gives single service with id in the param.

app.get(['/service', '/service/id/:id'], function(req, res) {});
like image 34
Arun Killu Avatar answered Sep 22 '22 11:09

Arun Killu