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

知道吗?


当前回答

在使用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'));
});

其他回答

在开发应用程序时,我们需要以以下方式定义PORT:

const port = process.env.PORT || 4000; // PORT must be in caps

在将应用程序部署到服务器时,添加以下方法:

app.listen(port, () => {
 console.info("Server started listening.");
});

我们可以在本地运行主机名时将主机名作为第二个参数传递。但是在将其部署到服务器时,应该删除主机名参数。

app.listen(port, hostName, () => {
  console.info(`Server listening at http://${hostName}:${port}`);
});

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

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

server.listen(5000);

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

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

To:

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

我的情况是,我在启动时运行数据库脚本,花费了很长时间。我在部署完成后手动运行npm start来解决这个问题。

Heroku动态地为你的应用程序分配端口,所以你不能将端口设置为一个固定的数字。Heroku将端口添加到env,所以你可以从那里拉它。让我们来听听这个:

.listen(process.env.PORT || 5000)

这样,当你在本地测试时,它仍然会监听端口5000,但它也可以在Heroku上工作。重要提示- PORT字必须大写。

你可以在这里查看Node.js上的Heroku文档。