在Express中使用子路由器时,获取完整的路由器模式?

假设我在以下Express应用程序中请求HTTP端点GET /foobar/baz ,我如何通过req对象获取用于匹配整个URL的原始模式(即/foo(bar)?/:id ):

 var app = express() var sub = express.Router() sub.get('/:id', function (req, res, next) { // if `/foobar/baz` is requested: console.log(req.url) // '/baz' console.log(req.baseUrl) // '/foobar' console.log(req.originalUrl) // '/foobar/baz' console.log(req.route.path) // '/:id' }) app.use('/foo(bar)?', sub) 

使用req.route.path可以访问子路由模式,它给了我/:id ,但是父路由模式/foo(bar)? 似乎无法获得。

您可以使用mountpath属性

app.mountpath属性是安装子应用程序的path模式。

 var app = express() var sub = express.Router() sub.get('/:id', function (req, res, next) { // if `/foobar/baz` is requested: console.log( sub.mountpath ); // '/foo(bar)?' console.log(req.route.path) // '/:id' }) app.use('/foo(bar)?', sub);