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

知道吗?


当前回答

我的情况是,我在启动时运行数据库脚本,花费了很长时间。我在部署完成后手动运行npm start来解决这个问题。

其他回答

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

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

当Heroku在服务器上绑定端口或主机名失败时发生错误。监听(port, [host], [backlog], [callback])。

Heroku需要的是.listen(process.env. port)或.listen(process.env. port)。港口,“0.0.0.0”)

所以更一般地,为了支持其他环境,使用这个:

var server_port = process.env.YOUR_PORT || process.env.PORT || 80;
var server_host = process.env.YOUR_HOST || '0.0.0.0';
server.listen(server_port, server_host, function() {
    console.log('Listening on port %d', server_port);
});

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

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

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

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

:

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

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

将监听端口从3000更改为(process.env.)。PORT || 5000)解决。