Heroku node.js 错误(Web 进程在启动后 60 秒内无法绑定到 $PORT)

新手上路,请多包涵

我有我的第一个 node.js 应用程序(在本地运行良好)-但我无法通过 heroku 部署它(也是第一次使用 heroku)。代码如下。所以不允许我写这么多代码,所以我只想说在本地以及在我的网络中运行代码没有问题。

  var http = require('http');
 var fs = require('fs');
 var path = require('path');

 http.createServer(function (request, response) {

    console.log('request starting for ');
    console.log(request);

    var filePath = '.' + request.url;
    if (filePath == './')
        filePath = './index.html';

    console.log(filePath);
    var extname = path.extname(filePath);
    var contentType = 'text/html';
    switch (extname) {
        case '.js':
            contentType = 'text/javascript';
            break;
        case '.css':
            contentType = 'text/css';
            break;
    }

    path.exists(filePath, function(exists) {

        if (exists) {
            fs.readFile(filePath, function(error, content) {
                if (error) {
                    response.writeHead(500);
                    response.end();
                }
                else {
                    response.writeHead(200, { 'Content-Type': contentType });
                    response.end(content, 'utf-8');
                }
            });
        }
        else {
            response.writeHead(404);
            response.end();
        }
    });

 }).listen(5000);

 console.log('Server running at http://127.0.0.1:5000/');

任何想法 ?

原文由 user428900 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 494
2 个回答

Heroku 动态地为您的应用程序分配一个端口,因此您不能将端口设置为固定数字。 Heroku 将端口添加到环境中,因此您可以从那里拉出它。切换你的听这个:

 .listen(process.env.PORT || 5000)

这样,当您在本地测试时,它仍然会监听端口 5000,但它也可以在 Heroku 上运行。 重要说明- PORT 字必须大写。

您可以在 此处 查看有关 Node.js 的 Heroku 文档。

原文由 redhotvengeance 发布,翻译遵循 CC BY-SA 4.0 许可协议

值得一提的是,如果您的代码未指定端口,则它 _不应是 web 进程_,而可能应该是 worker 进程。

因此,将您的 Procfile 更改为读取(填写您的特定命令):

 worker: YOUR_COMMAND

然后也在 CLI 上运行:

 heroku scale worker=1

原文由 zthomas.nc 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题