繁体   English   中英

在Express JS中按顺序获取req.params

[英]Getting req.params in order in Express JS

在Express中,有没有办法按照路由中定义的顺序从匹配路由传递参数?

我希望能够将路线中的所有参数应用到另一个函数。 问题是这些参数不是预先知道的,所以我不能明确地通过名称引用每个参数。

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

打电话给GET: "/foo/bar/baz"

期望的输出(按此顺序):

foo
bar
baz

req.route.keys是一个有序的参数数组,其内容遵循{name:'first'}

所以,代码:

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

据我所知,通过快速路径params机制,这是一个非常简单的子系统。 我认为好老的req.path.split('/')在这里是你的朋友。

我相信你想要的是req.route.params对象。

Express文档中查看更多内容。

如果你不想使用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

这将是他们匹配的顺序

你的头衔有误导性。 你正在寻找解析路径,但你的标题是我在寻找获得参数时找到的,所以我会发一个答案。

我使用lodash将第一个参数(req.params)验证为Mongo / ObjectId。 在你的情况下,你可以用lodash键或值索引...

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.

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