Node.js/Express routing with get params


Question

Let's say I have get route like this:

app.get('/documents/format/type', function (req, res) {
   var format = req.params.format,
       type = req.params.type;
});

So if I make request like

http://localhost:3000/documents/json/mini

in my format and type variables will be 'json' and 'mini' respectively, but if I make request like

http://localhost:3000/documents/mini/json

not. So my question is: how can I get the same variables in different order?

1
48
12/14/2011 3:51:44 PM

Accepted Answer

Your route isn't ok, it should be like this (with ':')

app.get('/documents/:format/:type', function (req, res) {
   var format = req.params.format,
       type = req.params.type;
});

Also you cannot interchange parameter order unfortunately. For more information on req.params (and req.query) check out the api reference here.

132
6/9/2013 12:18:50 PM

For Query parameters like domain.com/test?format=json&type=mini format, then you can easily receive it via - req.query.

app.get('/test', function(req, res){
  var format = req.query.format,
      type = req.query.type;
});

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon