63

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?

maerics
  • 143,080
  • 41
  • 260
  • 285
Erik
  • 13,045
  • 47
  • 127
  • 205
  • 1
    You don't `documents/mini/json` is `format == mini` and `type == json`. URL's are not unordered bags of parameters – Raynos Dec 14 '11 at 15:38

2 Answers2

170

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.

verybadalloc
  • 5,698
  • 2
  • 30
  • 46
alessioalex
  • 60,463
  • 16
  • 153
  • 121
  • alessioalex Thank you for the response! – Erik Dec 14 '11 at 16:31
  • 8
    //var sanitizer = require('sanitizer'); var format = sanitizer.escape(req.params. format); You really should sanitize the result. Or else your website has a HUGE vulnerability – user3806549 Oct 12 '15 at 18:36
56

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;
});
Amit G
  • 2,173
  • 2
  • 21
  • 43
SCBuergel
  • 1,512
  • 15
  • 24