[英]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 ? 在Express中,有没有办法按照路由中定义的顺序从匹配路由传递参数?
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"
打电话给
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'}
. req.route.keys
是一个有序的参数数组,其内容遵循{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. 据我所知,通过快速路径params机制,这是一个非常简单的子系统。 I think good old
req.path.split('/')
is your friend here. 我认为好老的
req.path.split('/')
在这里是你的朋友。
I believe that what you want is the req.route.params
object. 我相信你想要的是
req.route.params
对象。
See more in the Express docs . 在Express文档中查看更多内容。
If the you don't want to use param ids but want their order then do this 如果你不想使用param id但想要他们的订单,那么就这样做
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. 我使用lodash将第一个参数(req.params)验证为Mongo / ObjectId。 In your case though you can index with lodash keys or values...
在你的情况下,你可以用lodash键或值索引...
req.route.keys did not work for me as well as req.params[0] req.route.keys不适用于我和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'); } }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.