Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

multiple conditional GET parameters

multiple conditional GET parameters

Problem

How can I merge these two get requests into one?

app.get('/:something/:else', function(req, res){
  res.render("something");
});

app.get('/:something', function(req, res){
  res.render("something");
});

I tried this and it didn't work.

app.get('(/:something|/:something/:else)', function(req, res){
  res.render("something");
});
Problem courtesy of: ThomasReggi

Solution

I am not 100% sure but I think you can do:

'/:something/:else?'

Otherwise you can either store the middleware function in a variable:

var m = function (req, res) { }
app.get('/one', m);
app.get('/two', m);

Or you can use a regular expression.

app.get(/^\/commits\/(\w+)(?:\.\.(\w+))?$/, function(req, res){
  var from = req.params[0];
  var to = req.params[1] || 'HEAD';
  res.send('commit range ' + from + '..' + to);
});

There is some info on the Express.js site: http://expressjs.com/api.html#app.VERB

The author also has a client-side library that is based on Express.js routing so maybe you can find more info there. That's where I could the '?' example. The library is called page.js and can be found: http://visionmedia.github.com/page.js/

Solution courtesy of: Pickels

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

multiple conditional GET parameters

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×