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

知道吗?


当前回答

使用process.env.PORT || 3000作为端口。

这将在可用时使用Heroku的端口,如果不可用则使用端口3000(例如,本地测试)

您可以将3000更改为您想要的任何值,例如8080

其他回答

在我的例子中,端口和主机都不是问题。index.js被分成了两个文件。server.js:

//server.js
const express = require('express')
const path = require('path')

const app = express()

app.use(express.static(path.resolve(__dirname, 'public')));
// and all the other stuff
module.exports = app

//app.js
const app = require('./server');
const port = process.env.PORT || 3000;
app.listen(port, '0.0.0.0', () => {
    console.log('Server is running s on port: ' + port)
});

从包中。我们运行node app。js。

显然这就是问题所在。一旦我将两者合并到一个文件中,Heroku应用程序就会按预期部署。

值得一提的是,如果你的代码没有指定端口,那么它就不应该是一个web进程,而应该是一个工作进程。

因此,将你的Procfile更改为read(填入你的特定命令):

worker: YOUR_COMMAND

然后在CLI上运行:

heroku scale worker=1

在我的例子中,我使用了来自https://hapijs.com/的例子

来解决我替换的问题

server.connection({ 
    host: 'localhost', 
    port: 8000 
});

server.connection({
    port: process.env.PORT || 3000 
});

我的问题是当部署到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显然不一样。

这是格兰桑特的功劳。

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

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

To:

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