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

知道吗?


当前回答

编辑package.json:

...
"engines": {
"node": "5.0.0",
"npm": "4.6.1"
},
...

和Server.js:

...
var port = process.env.PORT || 3000;
app.listen(port, "0.0.0.0", function() {
console.log("Listening on Port 3000");
});
...

其他回答

在我的例子中,端口和主机都不是问题。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应用程序就会按预期部署。

不能为port设置一个固定的数字,heroku使用process.env.PORT动态分配它。但是你可以同时添加它们,就像这个process.env.PORT || 5000。Heroku将使用第一个,而您的本地主机将使用第二个。

您甚至可以添加回调函数。请看下面的代码

app.listen(process.env.PORT || 5000, function() {
    console.log("Server started.......");
});

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

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

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

在heroku中重新启动所有dynos对我来说是有用的

我遇到了同样的问题,因为我没有定义Procfile。提交一个文本文件到应用程序的根目录Procfile,不带文件扩展名。这个文件告诉Heroku运行哪个命令来启动应用程序。

web: node app.js