我为一项服务拥有不同的软件产品,需要将其部署到一台服务器上。客户端是使用 React 构建的,并通过 create-react-app 进行build设置,而服务器则运行 Node.js 和 Express。
当我从服务器提供单个应用程序时,它是按以下方式完成的:
// App.js
// ...
// Entry point for data routes (API)
app.use('/data', indexRoute);
if(process.env.NODE_ENV !== 'development') {
app.use(express.static(path.join(__dirname, 'build-client')));
app.get('/*', function(req, res) {
return res.sendFile(path.resolve( __dirname, 'build-client' , 'index.html'));
});
}
我希望能够从服务器提供多个应用程序。我该怎么做?
我尝试的是为 Assets 连接不同的静态路径,并将具有不同名称的客户端分开,尽管它不起作用。像这样:
// App.js
// ...
// Entry point for data routes (API)
app.use('/data', indexRoute);
if(process.env.NODE_ENV !== 'development') {
app.use(express.static(path.join(__dirname, 'build-client')));
app.use(express.static(path.join(__dirname, 'build-admin')));
app.get('/client/*', function(req, res) {
return res.sendFile(path.resolve( __dirname, 'build-client' , 'index.html'));
});
app.get('/admin/*', function(req, res) {
return res.sendFile(path.resolve( __dirname, 'build-client' , 'index.html'));
});
}
我也尝试过这样做,但是 Express 抛出错误:未指定默认引擎且未提供扩展名:
if(process.env.NODE_ENV !== 'development') {
// Admin paths
app.use('/admin', express.static(path.join(__dirname, 'build-admin')));
app.get('/admin/*', function(req, res) {
return res.sendFile(path.resolve( __dirname, 'build-admin' , 'index.html'));
});
// Site paths
app.use('/', express.static(path.join(__dirname, 'build-client')));
app.get('/*', function(req, res) {
return res.sendFile(path.resolve( __dirname, 'build-client' , 'index.html'));
});
}
我怎样才能完成这个或类似的事情?
最佳答案
经过一番修改后,我无需使用虚拟主机即可实现这一目标。我使用了您在问题中给出的第一个想法,但我将主应用程序留在了根目录(即 /
)。
// when going to `/app2`, serve the files at app2/build/* as static files
app.use('/app2', express.static(path.join(__dirname, 'app2/build')))
// when going to `/`, serve the files at mainApp/build/* as static files
app.use(express.static(path.join(__dirname, 'mainApp/build')))
// These are necessary for routing within react
app.get('app2/*', (req, res) => {
res.sendFile(path.join(__dirname + '/app2/build/index.html'))
})
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname + '/mainApp/build/index.html'));
});
在此之后,我进入 mainApp/package.json
并添加
"proxy": "http://localhost:4141"
:4141
是 Express 服务器运行的端口。此行将使对 fetch('/some/route')
的调用返回到服务器,而不是返回到您的 React 应用程序本身。
最后,我们转到 app2/package.json
并添加
"proxy": "http://localhost:4141/app2",
"homepage": "/app2"
我相信这里的键是“homepage”
键。据我理解,当 React 启动时,它会在其主页上搜索一些静态文件,如果没有 "homepage"
片段,我只能得到空白屏幕或 mainApp。
我希望这对那里的人有帮助!
<小时/>编辑
我已经从通过我的 Express 服务器为我的 create-react-apps 提供服务更改为通过 netlify 为它们提供服务。现在我不需要担心这个快速设置,或者 package.json
中的主页 key 。 Express 服务器独立运行,React 应用程序仍然可以使用相同的 api,并且部署更加容易。使用 netlify 进行设置非常简单。
关于node.js - 在 Express 中通过客户端路由为多个 React 应用程序提供服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47416277/