Express.js routing: optional splat param?
This works for /path and /path/foo on express 4, note the *
before ?
.
router.get('/path/:id*?', function(req, res, next) {
res.render('page', { title: req.params.id });
});
I just had the same problem and solved it. This is what I used:
app.get('path/:required/:optional*?', ...)
This should work for path/meow
, path/meow/voof
, path/meow/voof/moo/etc
...
It seems by dropping the /
between ?
and *
, the last /
becomes optional too while :optional?
remains optional.
Will this do what you're after?
app.all('/path/:namedParam/:optionalParam?',function(req,res,next){
if(!req.params.optionalParam){
// do something when there is no optionalParam
} else {
// do something with optionalParam
}
});
More on Express' routing here, if you haven't looked: http://expressjs.com/guide/routing.html