Node.js/Express routing with get params

node.jsExpress

node.js Problem Overview


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?

node.js Solutions


Solution 1 - node.js

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.

Solution 2 - node.js

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;
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionErikView Question on Stackoverflow
Solution 1 - node.jsalessioalexView Answer on Stackoverflow
Solution 2 - node.jsSCBuergelView Answer on Stackoverflow