有谁知道是否有可能获得用于触发路线的路径?
例如,假设我有这个:
app.get('/user/:id', function(req, res) {});
Run Code Online (Sandbox Code Playgroud)
使用以下简单的中间件
function(req, res, next) {
req.?
});
Run Code Online (Sandbox Code Playgroud)
我希望能够进入/user/:id中间件,但事实并非如此req.url.
gus*_*nke 26
你想要的是什么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' ] }
Run Code Online (Sandbox Code Playgroud)
http://expressjs.com/api.html#req.route
编辑:
正如评论中所解释的那样,进入req.route中间件很困难/很困难.路由器中间件是填充req.route对象的中间件,它可能比您正在开发的中间件低.
通过这种方式,req.route只有req在Express自身执行之前,您可以使用挂钩到路由器中间件来解析它.
rob*_*lep 12
FWIW,另外两个选择:
// this will only be called *after* the request has been handled
app.use(function(req, res, next) {
res.on('finish', function() {
console.log('R', req.route);
});
next();
});
// use the middleware on specific requests only
var middleware = function(req, res, next) {
console.log('R', req.route);
next();
};
app.get('/user/:id?', middleware, function(req, res) { ... });
Run Code Online (Sandbox Code Playgroud)