【问题标题】:Heroku App Keeps Crashing Because Port is UndefinedHeroku 应用程序不断崩溃,因为端口未定义
【发布时间】:2021-06-03 16:00:53
【问题描述】:

这是我在 server.js 文件中的设置:

const express = require('express');
const app = express();

const host = '0.0.0.0';
const PORT = process.env.PORT || 5001;

app.listen(PORT, host, () => {
  console.log(`RABC Server is listening on port ${PORT}!`)
});

app.use(express.static('public'))

这是我的 Procfile 中的内容:

web:nodemon server.js 

这是我收到的错误:

Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch

这是我在登录端口时得到的:

PORT的值为:undefined

在我的 package.json 脚本中,我有:

 "scripts": {
    "start": "node server.js", 
    "build": "sanity build"
 }

我没有 .env 文件,我不确定我是否应该有一个,以及其中有什么。

当我运行“heroku 本地网络”并在本地托管时,一切正常。

我一生中从未部署或托管过应用程序,这是我的第一次。

【问题讨论】:

    标签: node.js express heroku


    【解决方案1】:

    server.js 更新为,

    const express = require('express');
    const app = express();
    const PORT = process.env.PORT || 5001;
    
    app.use(express.static('public'))
    
    app.listen(PORT, () => {
      console.log(`RABC Server is listening on port ${PORT}!`)
    });
    
    

    app.listen移到最后,

    使用逻辑和安全的初始化顺序只是一个约定,您首先配置服务器,然后再启动它。

    参考:why app.listen should be at the end after all the requests? also why is it necessary?

    另外,将 Procfile 更新为

    web:npm run start
    

    【讨论】:

    • 非常感谢你,这简直要了我的命,你不知道这对我有多大帮助。
    • 太棒了!我很高兴我能提供帮助!干杯!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-12
    • 2017-10-23
    • 2014-08-22
    • 2013-02-04
    • 1970-01-01
    相关资源
    最近更新 更多