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

知道吗?


当前回答

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

其他回答

在使用yeoman的angular-fullstack生成项目时,我也有同样的问题,删除IP参数对我有用。

我替换了这段代码

server.listen(config.port, config.ip, function () {
  console.log('Express server listening on %d, in %s mode', config.port, app.get('env'));
});

server.listen(config.port, function () {
  console.log('Express server listening on %d, in %s mode', config.port, app.get('env'));
});

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

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

改变这一行

app.listen(port);

to

app.listen(process.env.PORT, '0.0.0.0');

会有用的

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

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

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

从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。