Express v4:如何在参数中间件之前运行特定于路由的中间件
Express v4: How do I run route-specific middleware before param middleware?
长话短说,我有一个相当奇怪的路由场景,我需要在调用参数中间件之前调用中间件:
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.use(/^'/[^'/]*$/, function(req, res, next) {
});
相关文章:
- 什么'在Express中路由时,应用程序级中间件和路由器级中间件之间的区别是什么
- Expressjs:如何跨路由共享路由中间件
- 节点-如何在POST路由中间件中访问请求
- 使用虚拟主机中间件在 Express 中按子域指定路由
- 快速 - 路由中间件 如何确定响应视图是否已呈现
- Express JS - 对路由和中间件使用匿名函数
- 如何将快速路由处理传递给下一个中间件并破坏当前代码块
- Express :如何将中间件独占添加到路由器对象中的大型路由列表中
- 禁用特定路由上特定谓词的身份验证中间件
- NodeJs 路由中间件错误
- Express v4:如何在参数中间件之前运行特定于路由的中间件
- 我的错误处理程序如何优先于早期的中间件
- 创建路由得到 Router.use() 的错误需要中间件功能
- 从快速中间件中排除路由
- 在任何路由之前运行的中间件
- 通过Express中间件将req.body传递到路由
- 在nodejs中使用带有handlerbs的路由中间件
- Express.js:从路由处理程序中调用next(error)会调用全局错误处理中间件吗?
- NodeJS Express Router,在中间件和路由之间传递解码后的对象
- Falcor路由特定中间件