我使用 Express 和 React 来构建一个同构的应用程序。我想使用具有固定路径的系列 URL 的反应,如:hostname/admin/xxx
,hostname/admin/yyy
,hostname/admin/zzz
。
在 Express 中,路由器是:
// in server.js file
app.use('/admin', admin);
// in admin.js router file
router.get('*', (req, res) => {
match() // react-router's match method
}
在react-router
的routes
文件中它是:
<Route path='/' component={Admin}>
<Route path='child' component={Child} />
</Route>
当我访问hostname/admin
时,服务器呈现可以完全匹配路由,但浏览器抛出错误:Warning: [react-router] Location "/admin" did not match any routes
。
如果我将routes
更改为
<Route path='/admin' component={Admin}>
<Route path='child' component={Child} />
</Route>
服务器呈现无法匹配任何路由。
我认为问题是,对于服务器渲染,path
是'/'
,但对于客户端,它是'/admin'
。除了在 Express 中使用app.use('/', admin)
之外,我该如何解决?
1 回答
我的最终解决方案是在
match()
方法中将'/admin'
添加到location
属性: