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

知道吗?


当前回答

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

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

server.listen(5000);

其他回答

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

我也有同样的问题,但我的环境变量设置得很好,npm和node的版本在package.json中指定。我发现这是因为,在我的情况下,Heroku需要在package.json中指定“start”:

  "scripts": {
    "start": "node index.js"
  }

把这个加到我的包里之后。我的节点应用程序成功部署在Heroku。

我浪费了一整天的时间思考后台有问题。在经历了这里所有的解决方案和彻底的日志检查后,意识到这是前端反应App.js有问题。

我换了每个

Axios.post(`${process.env.REACT_APP_BASE_URL}/createOrder`, {

})

to

Axios.post(`/createOrder`, {

})

它成功了!

显然,react文件与heroku部署无关!

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

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