gpt4 book ai didi

node.js - 在 Express 中使用子路由器时获取完整的路由器模式?

转载 作者:太空宇宙 更新时间:2023-11-03 21:58:09 24 4
gpt4 key购买 nike

假设我在以下 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属性(property)

The app.mountpath property is the path pattern(s) on which a sub app was mounted.

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);

关于node.js - 在 Express 中使用子路由器时获取完整的路由器模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34772579/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com