问题描述
我正在努力将 Web 应用程序部署到 Heroku。一切似乎都很好,没有显示错误,但我只看到一个空白页。
我一直在互联网上搜索并尝试了我所看到的一切,但似乎无法找到答案。
server.js:
app.use(express.static(path.join(__dirname,'../frontend/build')));
app.get('*',(req,res) =>
res.sendFile(path.join(__dirname,'../frontend/build/index.html'))
);
文件夹:
我不知道还要附加什么,请告诉我,我会提供。非常感谢您,这对我来说真的很重要
解决方法
一般来说,
如果您想将整个 MERN 应用程序部署到 Heroku,请首先将 heroku-postbuild
脚本添加到 package.json
就您而言,由于您有分别包含客户端和服务器的目录 frontend
、backend
。
将这些脚本添加到您的 package.json
,这些脚本将在推送到 heroku 后build
您的 React 前端。
...
"scripts": {
"install-client":"cd frontend && npm install"
"heroku-postbuild": "npm run install-client && npm run build"
}
...
现在在您的 server.js
文件中,
...
const path = require('path');
app.use(express.static(path.join(__dirname,'../frontend/build')));
app.get('/',function (req,res) {
res.sendFile(path.join(__dirname,'../frontend/build','index.html'));
});
...
现在,如果您需要使用客户端路由(React Router)将 /
更新为 /*
,如下所示,
app.get('/*',res) {
res.sendFile(path.join(__dirname,'index.html'));
});
我认为这应该可以解决问题。
参考:https://create-react-app.dev/docs/deployment/
,您是否正在尝试从 heroku 中同时部署后端和前端?
过去我使用 heroku 作为我的后端,使用 netlify 来部署我的前端