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

知道吗?


当前回答

改变这一行

app.listen(port);

to

app.listen(process.env.PORT, '0.0.0.0');

会有用的

其他回答

如果您像我一样,正在配置Heroku以运行包中的脚本。json文件部署,确保你没有硬编码的值PORT在该脚本!如果您这样做了,您就会像我一样,花一个小时试图弄清楚为什么会得到这个错误。

在heroku中重新启动所有dynos对我来说是有用的

不能为port设置一个固定的数字,heroku使用process.env.PORT动态分配它。但是你可以同时添加它们,就像这个process.env.PORT || 5000。Heroku将使用第一个,而您的本地主机将使用第二个。

您甚至可以添加回调函数。请看下面的代码

app.listen(process.env.PORT || 5000, function() {
    console.log("Server started.......");
});

我花了很多时间来寻找根本原因,最终我发现这个超时(60s)是可以调整的。在这里,你可以将60秒改为120秒,甚至更久。这对我有用,希望能帮助到其他人!

虽然这里的大多数答案都是有效的,但对我来说,问题是我运行了长进程作为npm run start的一部分,这导致了超时。

我在这里找到了解决方案,总结一下,我只需要将npm run build移动到postinstall任务。

换句话说,我改变了这个:

"start": "npm run build && node server.js"

:

"postinstall": "npm run build",
"start": "node server.js"

仔细想想,这完全是有道理的,因为随着我的应用不断发展,这种错误(以前偶尔出现)变得越来越普遍。