Node.JS应用程序未在用户定义的端口号上的heroku上运行

时间:2017-04-27 15:11:45

标签: node.js heroku

我在Node.JS做了一个基本的应用程序。我正在尝试将其部署在成功部署的heroku服务器上。

我可以在localhost上访问此应用程序,但它不在heroku服务器上运行。它试图开始然后自动杀死。

index.js

var http = require("http");   
http.createServer(function (request, response) {

   // Send the HTTP header 
   // HTTP Status: 200 : OK
   // Content Type: text/plain
   response.writeHead(200, {'Content-Type': 'text/plain'});

   // Send the response body as "Hello World"
   response.end('Hello World\n');
}).listen(80);

的package.json

{
  "name": "powerful-escarpment",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "node index.js"
  },
  "author": "",
  "license": "ISC"
}

server.logs

2017-04-27T15:05:52.119923+00:00 heroku[web.1]: State changed from crashed to starting
2017-04-27T15:05:53.414613+00:00 heroku[web.1]: Starting process with command `npm start`
2017-04-27T15:05:56.563672+00:00 app[web.1]: 
2017-04-27T15:05:56.563686+00:00 app[web.1]: > powerful-escarpment@1.0.0 start /app
2017-04-27T15:05:56.563687+00:00 app[web.1]: > node index.js
2017-04-27T15:05:56.563687+00:00 app[web.1]: 
2017-04-27T15:05:56.836819+00:00 heroku[web.1]: Process exited with status 0
2017-04-27T15:05:56.849642+00:00 heroku[web.1]: State changed from starting to crashed

4 个答案:

答案 0 :(得分:4)

您的应用失败,因为您使用的是静态端口80。默认情况下Heroku不给端口80(不知道为什么,可能是因为它众所周知)。锻炼是使用动态端口号。

这是我刚刚创建的一个简单应用(https://infinite-savannah-21740.herokuapp.com/

Procfile:

web: node index.js

Index.js

const express = require('express');
const path = require('path');

// Server
var server = express();
var port = process.env.PORT || 8080; // <== this is must

server.get('/', (req, res) => {

    res.send("Working")
})

server.listen(port, () => {
    console.log("Listening on port: " + port)
})

答案 1 :(得分:3)

我认为这是因为你正在定义端口错误的方式,它应该是类似的,

var http = require("http");   
http.createServer(function (request, response) {

   // Send the HTTP header 
   // HTTP Status: 200 : OK
   // Content Type: text/plain
   response.writeHead(200, {'Content-Type': 'text/plain'});

   // Send the response body as "Hello World"
   response.end('Hello World\n');
}).listen(process.env.PORT || 3000);

其实我也是新手,但它对我有用

答案 2 :(得分:3)

Heroku设置应用程序运行的端口,然后将其绑定到端口80.要获取Heroku设置的端口,您需要阅读process.env.PORT

const http = require("http");  

const port = process.env.PORT || 80;

http.createServer(function (request, response) {

   // Send the HTTP header 
   // HTTP Status: 200 : OK
   // Content Type: text/plain
   response.writeHead(200, {'Content-Type': 'text/plain'});

   // Send the response body as "Hello World"
   response.end('Hello World\n');
}).listen(port);

答案 3 :(得分:1)

我不确定,但如果您收听端口进程,请查看是否有所作为.env.PORT || 80而不是80端口。

.listen(process.env.PORT || 80);
相关问题