我有我的第一个node.js应用程序(本地运行良好)-但我无法通过heroku部署它(第一次w/ 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/');

知道吗?


当前回答

Heroku动态地为你的应用程序分配端口,所以你不能将端口设置为一个固定的数字。Heroku将端口添加到env,所以你可以从那里拉它。让我们来听听这个:

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

这样,当你在本地测试时,它仍然会监听端口5000,但它也可以在Heroku上工作。重要提示- PORT字必须大写。

你可以在这里查看Node.js上的Heroku文档。

其他回答

在所有我尝试过的解决方案中,没有人能像预期的那样工作,我研究了heroku默认情况下的。env文件应该保持约定的端口,进程。env。PORT, heroku默认情况下会寻找关键字PORT。

取消任何重命名,例如APP_PORT=,而是在env文件中使用PORT=。

在我的例子中,我使用了来自https://hapijs.com/的例子

来解决我替换的问题

server.connection({ 
    host: 'localhost', 
    port: 8000 
});

server.connection({
    port: process.env.PORT || 3000 
});

我会建议你很好地阅读日志,以便轻松排除故障。 如果你引用一个PORT作为环境变量(env),请确保它是PORT而不是PORT,因为heroku会在你部署应用程序时自动分配一个PORT号。process.env.PORT不是process.env.PORT

值得一提的是,如果你的代码没有指定端口,那么它就不应该是一个web进程,而应该是一个工作进程。

因此,将你的Procfile更改为read(填入你的特定命令):

worker: YOUR_COMMAND

然后在CLI上运行:

heroku scale worker=1

我也遇到了同样的问题,我可以解决这个问题,将'localhost'替换为'0.0.0.0'的IP