首页 文章

网址与 react-router 中的任何路线都不匹配

提问于
浏览
1

我使用 Express 和 React 来构建一个同构的应用程序。我想使用具有固定路径的系列 URL 的反应,如:hostname/admin/xxxhostname/admin/yyyhostname/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-routerroutes文件中它是:

<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 回答

  • 0

    我的最终解决方案是在match()方法中将'/admin'添加到location属性:

    match({
        routes,
        location: '/admin' + req.url
      }, (error, redirectLocation, props) => {
    });
    

相关问题