反应脚本构建 heroku Web 进程无法绑定到 $PORT 问题

react-scripts build heroku Web process failed to bind to $PORT issue

在 heroku-20 nodejs dyno

上有问题 运行 react-scripts build

Heroku 运行 npm start

"prestart": "cd client && npm install && npm run build",
"start": "NODE_ENV=prod node server/server"

client/package.json

"start": "react-scripts start",
"build": "react-scripts build"

日志:

2021-06-04T21:12:57.806280+00:00 app[web.1]: > react-scripts build
Creating an optimized production build...
2021-06-04T21:13:06.794538+00:00 heroku[web.1]: Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch
2021-06-04T21:13:06.845028+00:00 heroku[web.1]: Stopping process with SIGKILL
2021-06-04T21:13:06.939986+00:00 heroku[web.1]: Process exited with status 137
2021-06-04T21:13:07.001538+00:00 heroku[web.1]: State changed from starting to crashed
2021-06-04T21:13:10.445223+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=...

在 server.js 上,它具有以下内容:

const port = process.env.PORT || 5000;
...
if (process.env.NODE_ENV == 'prod'){
  app.use(express.static(path.join(__dirname, '../client/build')));
}
app.use((req, res, next) => {
  res.header("Access-Control-Allow-Origin", process.env.CLIENT_BASE); // domain of the incoming request
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});
...
app.listen(port, () => console.log(`Listening on port ${port}`));

/client/.env 和根 .env 中还有一些 REACT_APP_ 变量用于服务器端变量。这些在 Heroku dyno Settings, Config Vars

中定义

预期的结果是 heroku react-script build 应该为客户端生成一个 build/ 文件夹,节点服务器使用它来服务静态和启用 CORS,因为它在本地工作。
实际结果是 heroku 崩溃见日志

我将构建脚本(react-scripts 构建)从 "start""prestart" 移动到 "build""heroku-postbuild",这解决了问题。我认为 "prestart:" 做的太多了,超出了 heroku 60s 端口绑定限制。
"start": 应该只用于执行代码