Reputation: 12730
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
Upvotes: 3
Views: 5975
Reputation: 4803
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');
}
}
Upvotes: 0
Reputation: 12730
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]);
}
}
Upvotes: 1
Reputation: 48003
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
Upvotes: 0
Reputation: 41440
I believe that what you want is the req.route.params
object.
See more in the Express docs.
Upvotes: 0
Reputation: 146114
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.
Upvotes: 0