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

知道吗?


当前回答

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

其他回答

我有一个类似的问题,试图解决它几个小时(H10 GET=/)。我尝试改变PORT,但没有结果。事实证明,解决方法很简单。我修改了包里的一行。json文件。从nodemon到node,成功了:

"scripts": {
"start": "nodemon app.js"

To:

 "scripts": {
 "start": "node app.js"

在所有我尝试过的解决方案中,没有人能像预期的那样工作,我研究了heroku默认情况下的。env文件应该保持约定的端口,进程。env。PORT, heroku默认情况下会寻找关键字PORT。

取消任何重命名,例如APP_PORT=,而是在env文件中使用PORT=。

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

我的问题是当部署到heroku时,我得到了一个错误:

Web进程在启动后60秒内未能绑定到$PORT

当运行heroku日志时——终端中的tail。但是当我在本地运行服务器时,应用程序将按预期运行。

我在index.js文件(服务器文件)中有这个

const PORT = process.env.port || 4000

app.listen(PORT, () => {
  console.log(`Server listening on port ${PORT}`)
})

但是应该有这个

const PORT = process.env.PORT || 4000

app.listen(PORT, () => {
  console.log(`Server listening on port ${PORT}`)
})

使用process.env。PORT,而不是process.env。port,因为port和port显然不一样。

这是格兰桑特的功劳。

从heroku bash进程中,使用选项解析器(如yargs)将$PORT的值传递给节点应用程序。

下面是一个示例,说明如何做到这一点。在脚本对象上,在包内。添加一个启动方法"node server——port $ port "。

在你的服务器文件中,使用yargs从start方法的port选项(——port $ port)中获取值:

const argv = require('yargs').argv;
const app = require('express')();

const port = argv.port || 8081;

app.listen(argv.port, ()=>{
    console.log('Probably listening to heroku $PORT now ', argv.port); // unless $PORT is undefined, in which case you're listening to 8081.
});

现在当你的应用程序启动时,它将绑定到动态设置的值$PORT。