Heroku + node.js エラー (Web プロセスが起動後 60 秒以内に $PORT にバインドできませんでした) 質問する

Heroku + node.js エラー (Web プロセスが起動後 60 秒以内に $PORT にバインドできませんでした) 質問する

最初の node.js アプリ (ローカルでは問題なく実行) がありますが、heroku 経由でデプロイできません (heroku も初めてです)。コードは以下の通りです。SO ではそれほど多くのコードを記述できないため、ローカルでもネットワーク内でもコードを実行しても問題は発生しません。

 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/');

何か案が ?

ベストアンサー1

Heroku はアプリにポートを動的に割り当てるため、ポートを固定番号に設定することはできません。Heroku は env にポートを追加するので、そこから取得できます。listen を次のように切り替えます。

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

こうすることで、ローカルでテストするときにポート 5000 をリッスンしますが、Heroku でも動作します。重要な注意- PORTという単語は大文字にする必要があります。

HerokuのドキュメントをNode.jsで確認することができます。ここ

おすすめ記事