如何将NodeJS App部署到Heroku?

时间:2017-06-06 00:51:11

标签: node.js git heroku

我正在使用NodeJS创建一个聊天应用程序,我想部署到Heroku。但是,通过使用Github部署,我收到错误:An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details.。有谁知道发生了什么?

  

这是一些代码,看看我做了什么。

    {
  "name": "chat",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node ./lib/index.js",
    "test": "jasmine"
  },
  "dependencies": {
    "express": "~4.13.1",
    "firebase": "^3.9.0",
    "request-promise": "^2.0.1",
    "socket.io": "^1.4.5"
  },
  "devDependencies": {
    "jasmine-sinon": "^0.4.0",
    "jscs": "^2.11.0",
    "proxyquire": "^1.7.4",
    "rewire": "^2.5.1",
    "sinon": "^1.17.3"
  }
}
  

index.js(服务器)

    var express = require('express');
var app = express();
var path = require('path');
var http = require('http').Server(app);
var io = require('socket.io')(http);

var routes = require('./routes');
var chats = require('./chat');



app.use(express.static(path.join(__dirname, '../public')));

routes.load(app);
chats.load(io);


var port = process.env.PORT || 3000;
app.listen(port);
console.log('Server is listening at port:' + port); 

1 个答案:

答案 0 :(得分:0)

我让应用程序在Heroku中运行。您的代码中的问题是您没有为heroku设置正确的端口。在您提供的代码中,您可以通过

设置正确的端口
var port = process.env.PORT || 3000;

但是,在您的GitHub项目中,您将端口硬编码为3000

http.listen(3000, function () {
  console.log('listening on *:3000');
});

相反,您想要做的是允许Heroku定义端口或默认为3000以进行开发,如此...

var process = require('process');

var port = process.env.PORT || 3000;
http.listen(port, function() {
  console.log("Server is listening on port: " + port);
});

完成后,部署到Heroku,您应该会看到您的应用正在运行。