我从一个目录静态地为我的网站提供服务。我有一个用于设置 URL 参数 roomCode
的动态路由。我希望此路径的所有路由都可以在不更改客户端上的 URL 的情况下为根索引页面提供服务(这样我仍然可以在我的 JavaScript 中使用 roomCode)。
这是我目前拥有的:
// direct rooms to the index page
app.use('/room/:roomCode([A-Z]{4})', (_, res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'))
})
// serve from the dist build
app.use(express.static(path.join(__dirname, 'dist')))
我不想手动发送 dist/index.html
文件,而是简单地将以下中间件的路由路径更改为 /
并让静态服务器发送文件。像这样:
// direct rooms to the index page
app.use('/room/:roomCode([A-Z]{4})', (_, res, next) => {
req.path = '/'
next()
})
// serve from the dist build
app.use(express.static(path.join(__dirname, 'dist')))
这样,当到达静态中间件时,它认为路径是 /
,因此它将在根处提供索引页。
这可能吗?
答案 0 :(得分:0)
要重新路由请求,您必须将 req.originalUrl
更改为新路由,然后使用 app._router.handle(req, res, next)
将其发送到路由器处理程序。
// direct rooms to the index page
app.use('/room/:roomCode([A-Z]{4})', (req, res, next) => {
// this reroutes the request without a redirect
// so that the clients URL doesn't change
req.originalUrl = '/'
app._router.handle(req, res, next)
})
// serve from the dist build
app.use(express.static(path.join(__dirname, 'dist')))
req.originalUrl 的文档有点混乱。它说:
<块引用>这个属性很像req.url;但是,它保留了原始请求 URL,允许您自由地重写 req.url 以用于内部路由目的。
这听起来好像如果您更改 req.url
,它将改变它的路由方式。然而,事实并非如此。它确实允许您更改它,然后在后面的中间件中手动检查它。但是中间件仍然会根据原始 URL 进行调用。因此,我们需要覆盖原来的URL并通过路由器发回。