node.js - 与 create-react-app 相关的 Heroku 部署问题
问题描述
我从 create-react-app 构建了一个反应应用程序,它使用基于 express 构建的 API。我正在尝试将应用程序部署到 heroku,但遇到了一些问题。这将是我的第一次部署。
最初,我通过使用在不同端口上运行的两台服务器将 express API 后端与 React 前端分开。然后我在应用程序的顶级 package.json 文件中同时启动两个服务器。
该项目如下所示:
app
|package.json
|client
|package.json
|public
|src
|server
|package.json
|app.js
当 webpack 为 React 应用程序启动开发服务器时,这在本地运行良好。然而,在部署时,Heroku 会将登录页面指向 express 服务器,而不是 react-app 主页,从而导致很多什么都没有。
我想知道我是否应该:
A. 通过单个 express 服务器运行所有内容,然后从那里提供 react 应用程序
B. 找到一种方法来运行两个服务器,但指向 React 应用服务器。
这是顶级 package.json 文件
{
"name": "",
"version": "2.0.0",
"description": "",
"main": "app.js",
"dependencies": {
"@material-ui/icons": "^4.9.1",
"concurrently": "^5.3.0",
"cors": "^2.8.5",
"@material-ui/core": "^4.11.0",
"axios": "^0.20.0",
"chart.js": "^2.9.4",
"material-table": "^1.69.1",
"query-string": "^6.13.2",
"react": "^16.13.1",
"react-chartjs-2": "^2.10.0",
"react-dom": "^16.13.1",
"react-scripts": "^3.4.3",
"spotify-web-api-js": "^0.22.1",
"bluebird": "^3.7.2",
"body-parser": "^1.19.0",
"cookie-parser": "1.3.2",
"dotenv": "^8.2.0",
"express": "~4.0.0",
"express-session": "^1.17.1",
"handlebars": "^4.7.6",
"querystring": "~0.2.0",
"request": "~2.34.0",
"uuid": "^8.3.0"
},
"devDependencies": {},
"scripts": {
"start": "concurrently \"npm run server\" \"npm run client\"",
"test": "echo \"Error: no test specified\" && exit 1",
"client": "cd client && npm start",
"server": "cd server && npm start"
},
"engines": {
"node": "12.16.2",
"npm": "6.14.4"
},
}
解决方案
A. 通过单个 express 服务器运行所有内容,然后从那里提供 react 应用程序
就部署的复杂性、性能和安全性而言,这将是最佳选择。
为了进一步减少在 Heroku 部署期间出现问题的可能性,请考虑选择将您的解决方案容器化。您可以安装 Docker,构建容器并在本地运行它。在 Heroku 部署之后,在容器内运行的软件(例如 Express)无法(嗯,几乎)区分本地运行和云中运行。由于您在本地提供的运行时环境与 Heroku 的运行时环境之间的差异,它消除了许多部署问题。实际示例,它提供了执行七个命令的序列,以获取构建和部署 Express/React 的容器。我是作者。
推荐阅读
- uwp - Windows 10 UWP - 在不同机器上使用 BluetoothLE SDK 示例连接到 BLE 设备时出现问题
- javascript - 使用带有把手的 nodemailer 处理动态电子邮件
- angular - 使用 Angular 获取 KeycloakService 令牌
- javascript - 谷歌表单不要求权限谷歌脚本
- javascript - jQuery:动画位置不影响 DOM
- jquery - 实现分页时如何在select2中设置值
- sparql - SPARQL 带增量变量的空白节点 skolemization
- python - 将多个字符串参数传递给 Python 脚本
- c++ - 在向量中使用 size() 函数时出错
- react-native - react-native 如何在页面底部设置导航栏?