Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js/Express routing with get params

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?

like image 590
Erik Avatar asked Dec 14 '11 15:12

Erik


People also ask

How do you access GET parameters after Express?

Your query parameters can be retrieved from the query object on the request object sent to your route. It is in the form of an object in which you can directly access the query parameters you care about. In this case Express handles all of the URL parsing for you and exposes the retrieved parameters as this object.

How does Express define params?

In Express, route parameters are essentially variables derived from named sections of the URL. Express captures the value in the named section and stores it in the req. params property. You can define multiple route parameters in a URL.


1 Answers

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.

like image 102
alessioalex Avatar answered Oct 03 '22 04:10

alessioalex