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

知道吗?


当前回答

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

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

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

其他回答

编辑package.json:

...
"engines": {
"node": "5.0.0",
"npm": "4.6.1"
},
...

和Server.js:

...
var port = process.env.PORT || 3000;
app.listen(port, "0.0.0.0", function() {
console.log("Listening on Port 3000");
});
...

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

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

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

在我的例子中,我使用Babel plugin-transform-inline-environment-variables插件。显然,Heroku在进行部署时没有设置PORT env变量,因此process.env.PORT将被undefined取代,并且您的代码将回退到Heroku不知道的开发端口。

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

我遇到了同样的问题,因为我没有定义Procfile。提交一个文本文件到应用程序的根目录Procfile,不带文件扩展名。这个文件告诉Heroku运行哪个命令来启动应用程序。

web: node app.js