小编典典

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

js

我有我的第一个 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/');

任何想法 ?


阅读 192

收藏
2022-03-06

共1个答案

小编典典

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

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

这样,当您在本地测试时,它仍然会监听端口 5000,但它也可以在 Heroku 上运行。

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

2022-03-06