获取中间件的路由定义

有谁知道是否有可能得到用于触发路线的path?

例如,假设我有这个:

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.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 。 路由器中间件是填充req.route对象的中间件,它可能比您正在开发的中间件的层次低。

这样,获取req.route只有在挂钩到路由器中间件的时候才能parsingreq

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) { ... }); 

这种使用原型覆盖的诡计将有所帮助

  "use strict" var Route = require("express").Route; module.exports = function () { let defaultImplementation = Route.prototype.dispatch; Route.prototype.dispatch = function handle(req, res, next) { someMethod(req, res); //req.route is available here defaultImplementation.call(this, req, res, next); }; };