Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express.js routing: optional splat param?

I have a route that looks like this:

app.all('/path/:namedParam/*splat?',function(req,res,next){
  if(!req.params.length){
    // do something when there is no splat
  } else {
    // do something with splat
  }
});

however, this doesn't work - if I call path/foo/bar it hits the route, but if I call path/foo, it doesn't.

Is it possible to have an optional splat param, or do I have to use a regex to detect this?

Edit:

to be clearer, here are the requirements I'm trying to achieve:

  • the first and second params are required
  • the first param is static, the second is a named param.
  • any number of optional additional params can be appended and still hit the route.
like image 995
Jesse Avatar asked Apr 04 '12 22:04

Jesse


3 Answers

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 });
});
like image 160
Chris Avatar answered Nov 20 '22 21:11

Chris


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.

like image 77
Andreas Hultgren Avatar answered Nov 20 '22 23:11

Andreas Hultgren


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

like image 18
Dave Ward Avatar answered Nov 20 '22 23:11

Dave Ward