gpt4 book ai didi

javascript - express v4 : How do I run route-specific middleware before param middleware?

转载 作者:行者123 更新时间:2023-12-03 07:45:50 25 4
gpt4 key购买 nike

长话短说,我有一个相当奇怪的路由场景,我需要在调用参数中间件之前调用中间件:

router.param('foo', function (req, res, next, param) {
// Get the param value
...
next()
})

router.route('/:foo')
.all(function (req, res, next) {
// I want to run this before the router.param middleware
// but I don't want to run this on /:foo/bar
...
next()
})
.get(function (req, res, next) {
// Run this after the router.param middleware
...
res.send('foo')
})

router.route('/:foo/bar')
.get(function (req, res, next) {
// Run this after the router.param middleware
...
res.send('bar')
})

现在,我明白为什么参数中间件通常首先运行,但是有没有办法解决这个问题?

我尝试使用router.use没有这样的路径:

router.use(function (req, res, next) {
// I want to run this before the router.param middleware
// but I don't want to run this on /:foo/bar
...
next()
})

...并在 router.param 中间件之前调用它,但随后它也会被 /:foo/bar 调用。

最后,如果我将 router.use 这样的路径一起使用:

router.use('/:foo', function (req, res, next) {
// I want to run this before the router.param middleware
// but I don't want to run this on /:foo/bar
...
next()
})

...router.param 中间件首先被调用(如您所料)。

有办法做到这一点吗?

最佳答案

我绝不是正则表达式方面的专家,但您可以使用正则表达式来匹配路由。尽管可能有更好的方法,但这适用于您的特定用例。

router.use(/^\/[^\/]*$/, function(req, res, next) {

});

关于javascript - express v4 : How do I run route-specific middleware before param middleware?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35211050/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com