Url在反应路由器中不匹配任何路由
问题描述:
我使用Express和React构建同构应用。我想使用具有固定路径的系列url进行反应,如:hostname/admin/xxx
,hostname/admin/yyy
,hostname/admin/zzz
。Url在反应路由器中不匹配任何路由
在高速路由器是:
// 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)
?
答
我的最终解决方案是增加'/admin'
到location
财产match()
方法:
match({
routes,
location: '/admin' + req.url
}, (error, redirectLocation, props) => {
});