64

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
  • 151,642
  • 46
  • 269
  • 291
Erik
  • 14,060
  • 49
  • 132
  • 218
  • 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

173

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,768
  • 2
  • 33
  • 49
alessioalex
  • 62,577
  • 16
  • 155
  • 122
  • 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
58

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

app.get('/test', function(req, res){
  var format = req.query.format,
      type = req.query.type;
});
Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109
SCBuergel
  • 1,613
  • 16
  • 26