首页 > 解决方案 > react-scripts build heroku Web 进程未能绑定到 $PORT 问题

问题描述

react-scripts build在 heroku-20 nodejs dyno 上运行时出现问题

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的根目录中和根目录中也有一些 REACT_APP_变量。.env这些在 Heroku dyno Settings, Config Vars 中定义

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

标签: node.jsherokuenvironment-variablesportreact-scripts

解决方案


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


推荐阅读