在中间件获取路由定义 [英] Get route definition in middleware
问题描述
例如,假设我有这个:
app.get('/ user /:id',function(req,res){});
使用以下简单的中间件
function(req,res,next){
req。
});
我想要获得 / user /:id
在中间件中,这不是 req.url
。
你想要的是 req.route.path
。
例如:
app.get('/ user /:id?',function(req,res){
console.log(req。路线);
});
//输出像
{path:'/ user /:id?',
method:'get',
callbacks: [功能]],
键:[{name:'id',可选:true}],
regexp:/ ^ \ / user(?:\ /([^ \ / +?))?\ /?$ / i,
params:[id:'12']}
http://expressjs.com/api.html#req.route
编辑:
正如在中间件中得到 req.route
的意见是困难/骇人听闻的。路由器中间件是填充 req.route
对象的路由器中间件,它可能处于比正在开发的中间件更低的级别。
这样,只有在挂接到路由器中间件才能解析 req
req.route
code>给您,由Express本身执行。 Does anyone know if it's possible to get the path used to trigger the route?
For example, let's say I have this:
app.get('/user/:id', function(req, res) {});
With the following simple middleware being used
function(req, res, next) {
req.?
});
I'd want to be able to get /user/:id
within the middleware, this is not req.url
.
What you want is req.route.path
.
For example:
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
EDIT:
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.
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屋!