在中间件中获取路由定义 [英] Get route definition in middleware
问题描述
有谁知道是否可以获取用于触发路由的路径?
Does anyone know if it's possible to get the path used to trigger the route?
例如,假设我有这个:
app.get('/user/:id', function(req, res) {});
使用以下简单的中间件
function(req, res, next) {
req.?
});
我希望能够在中间件中获取 /user/:id
,这不是 req.url
.
I'd want to be able to get /user/:id
within the middleware, this is not req.url
.
推荐答案
你想要的是req.route.path
.
例如:
app.get('/user/:id?', function(req, res){
console.log(req.route);
});
// outputs something like
{ path: '/user/:id?',
method: 'get',
callbacks: [ [Function] ],
keys: [ { name: 'id', optional: true } ],
regexp: /^/user(?:/([^/]+?))?/?$/i,
params: [ id: '12' ] }
http://expressjs.com/api.html#req.route
正如评论中所解释的,在中间件中获取 req.route
很困难/很困难.路由器中间件是填充 req.route
对象的中间件,它的级别可能低于您正在开发的中间件.
As explained in the comments, getting req.route
in a middleware is difficult/hacky. The router middleware is the one that populates the req.route
object, and it probably is in a lower level than the middleware you're developing.
这样,只有在 Express 本身执行之前,您挂钩路由器中间件为您解析 req
,才能获得 req.route
.
This way, getting req.route
is only possible if you hook into the router middleware to parse the req
for you before it's executed by Express itself.
这篇关于在中间件中获取路由定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!