我试图通过一台服务器为多个 react 应用程序提供服务,每个应用程序都应该在其中有路由。 例如: 应用程序 1 将通过“/”然后“/about”“/pricing”等访问。 应用程序 2 将通过“/app2”访问,然后通过“/app2/register”“/app2/login”访问
我关注了这个问题:Serving multiple react apps with client-side routing in Express
它工作正常,但嵌套客户端内的路由似乎不起作用。
这是我的代码:
服务器.js:
//*** server.js
//**************
// Serve app 2 static files
app.use('/app2', express.static(path.join(__dirname, 'client_app2/build')));
// Serve app 1 static files
app.use(express.static(path.join(__dirname, 'client_app1/build')));
// Serve app 2 build index
app.get('/customer/*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'client_customer', 'build', 'index.html'));
});
// Serve app 1 build index
app.get('/*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'client_main', 'build', 'index.html'));
});
应用程序1:(主要的)
function App() {
return (
<Router>
<Fragment>
<h1>App 1 - Main App</h1>
<Switch>
<Route path='/about'>
<h2>About</h2>
</Route>
<Route exact path='/pricing'>
<h2>Pricing</h2>
</Route>
</Switch>
</Fragment>
</Router>
);
}
应用程序1 package.json:
"proxy": "http://localhost:80"
应用程序2:
function App() {
return (
<Router>
<Fragment>
<h1>App 1 (nested app)</h1>
<Switch>
<Route path='/login'>
<h2>Login</h2>
</Route>
<Route exact path='/register'>
<h2>Registration</h2>
</Route>
</Switch>
</Fragment>
</Router>
);
}
应用程序2 package.json:
"proxy": "http://localhost:80/app2",
"homepage": "/app2"
正如我所说,除了应用程序 2 内的路由之外,一切正常, soo 转到“app2/login”将与转到“app2/”相同。
也许我应该改变我的方法?
我应该提到我正在使用 Heroku 进行部署,这就是我使用端口 80 的原因 尽管即使我更改代码,代码似乎运行相同。
最佳答案
解决方案相当简单,嵌套客户端应用程序中的每个路由都应提供完整路径,如下所示:
应用程序 2(嵌套应用程序):
function App() {
return (
<Router>
<Fragment>
<Navbar />
<h1>Customer App (app 2 - nested)</h1>
<Switch>
<Route path='/app2/login'>
<h2>Login</h2>
</Route>
<Route exact path='/app2/register'>
<h2>Registration</h2>
</Route>
</Switch>
</Fragment>
</Router>
);
}
应用程序2 package.json:
"proxy": "http://localhost:80/app2",
"homepage": "/app2"
我原本以为代理和主页值意味着app2的根地址将是“/app2”,但看起来它仍然是“/”。 我不确定为什么会这样,如果有人知道并能够澄清这一点,那就太好了。
关于node.js - 在 Express 服务的多个 React 客户端内进行路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59408697/