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

知道吗?


当前回答

将监听端口从3000更改为(process.env.)。PORT || 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

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

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

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

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

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

:

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

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

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

我换了每个

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

})

to

Axios.post(`/createOrder`, {

})

它成功了!

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

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

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

server.listen(5000);