I have made a basic application in Node.JS. I am trying to deploy it on heroku server which is successfully deployed.
I am able to access this application on localhost however it is not running on heroku server. It tries to start then it kills automatically.
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
You app fails because you are using static port80. By default Heroku don't give port 80(don't know why, may be because its well known). Workout is to use dynamic port number.
Here a simple app I created just now(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)
})
I think that's because you are defining port wrong way,It should be something like,
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);
Actually I'm also newbie but it works for me
Heroku sets the port your application runs on, and then binds it to port 80. To get the port Heroku sets, you need to read 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);