Home » Nodejs » Optional GET parameter in Express route

Optional GET parameter in Express route

Posted by: admin November 30, 2017 Leave a comment

Questions:

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.

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.

Questions:
Answers:

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

Questions:
Answers:

You can also use regular expressions in routes. Perhaps something like:

app.get(/^\/foo\/start\/:start\/end\/:end(\/optional\/:value)?/, function (req, res, next) {

Questions:
Answers:

In this example, if the url is /hello or /hello/world it works. The ? makes the parameter become optional (express 4).

// app.js
var index = require('/routes/index');
app.use('/hello', index);

// routes/index.js
router.get('hello/:name?', function(req, res){
  var name = req.params.name;
  var data = {
    name: name
  };
  res.json(data);
});