我有我的第一个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不会绑定到本地主机。

您必须为主机传递0.0.0.0。

即使您使用了正确的端口。我们必须做出这样的调整:

# port (as described above) and host are both wrong
const host = 'localhost';
const port = 3000;

# use alternate localhost and the port Heroku assigns to $PORT
const host = '0.0.0.0';
const port = process.env.PORT || 3000;

然后你可以像往常一样启动服务器:

app.listen(port, host, function() {
  console.log("Server started.......");
});

你可以在这里看到更多细节:https://help.heroku.com/P1AVPANS/why-is-my-node-js-app-crashing-with-an-r10-error

其他回答

我意识到在请求端点中不需要端口号,因此端点是herokuapp.com,而不是herokuapp.com:5000。

listen()调用可以没有host和callback:

server.listen(5000);

当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);
});

对我来说,问题在于资本化。你知道,在数小时的编码之后,你的眼睛会错过一些小细节。

在我的代码中,我使用process.env.port而不是process.env。PORT,所以要注意,PORT环境变量必须是大写的。

请看下面的例子:

const PORT = process.env.PORT || 3000;
const HOST = process.env.HOST || '0.0.0.0';

const express = require('express');
const app = express();

app.listen(PORT, HOST, () => {
      console.log('Server started on ' + HOST + ':' + PORT);
})

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

就我而言,我有两个问题……

1)没有监听器,因为从另一个入口文件运行应用程序,这个运行脚本从包中删除。json“脚本”

2)用“Sequelize”而不是“Sequelize”区分大小写的问题