简体   繁体   中英

Getting req.params in order in Express JS

In Express, is there a way to get the arguments passed from the matching route in the order they are defined in the route ?

I want to be able to apply all the params from the route to another function. The catch is that those parameters are not known up front, so I cannot refer to each parameter by name explicitly.

app.get(':first/:second/:third', function (req) {
    output.apply(this, req.mysteryOrderedArrayOfParams); // Does this exist?
});

function output() {
    for(var i = 0; i < arguments.length; i++) {
        console.log(arguments[i]);
    }
}

Call on GET: "/foo/bar/baz"

Desired Output (in this order):

foo
bar
baz

req.route.keys is an ordered array of parameters whose contents follow {name:'first'} .

So, the code:

app.get(':first/:second/:third', function (req) {
    var orderedParams = [];
    for (var i = 0; i < req.route.keys; i++) {
        orderedParams.push(req.params[req.route.keys[i].name]);
    }
    output.apply(this, orderedParams);
});

function output() {
    for(var i = 0; i < arguments.length; i++) {
        console.log(arguments[i]);
    }
}

Not as far as I know via the express route params mechanism, which is a pretty simple subsystem. I think good old req.path.split('/') is your friend here.

I believe that what you want is the req.route.params object.

See more in the Express docs .

If the you don't want to use param ids but want their order then do this

app.get('/:0/:1/:2', function (req,res) {
    console.log(req.params);
    console.log(req.params[0]);
    console.log(req.params[1]);
    console.log(req.params[2]);
    res.end();
});

//output

[ 'a', 'b', 'c' ]
a
b
c
GET /a/b/c 200 5ms
[ 'c', 'b', 'a' ]
c
b
a
GET /c/b/a 200 1ms

which will be in the order they match

Your title is misleading. You are looking to parse the path but your title is what I found when looking for getting the params so I will post an answer.

I used lodash to validate the first parameter (req.params) as a Mongo / ObjectId. In your case though you can index with lodash keys or values...

req.route.keys did not work for me as well as req.params[0]

  if (_.size(req.params) === 1) { if (!mongoose.Types.ObjectId.isValid(_.values(req.params)[0])) { return res.status(500).send('Parameter passed is not a valid Mongo ObjectId'); } } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM