How do I deploy node app to heroku without using Express - javascript

I deployed my node.js app successfully to heroku however when I accessed the site there was an error saying
"Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch"
my code is
var router = require("./router.js");
// Create a web server
var http = require("http");
http.createServer(function (request, response) {
router.home(request, response);
router.user(request, response);
}).listen(1337);
console.log("Sever running at http://127.0.0.1:1337/");
I figured it has something to do with the port. There was a post similar to my problem Heroku + node.js error (Web process failed to bind to $PORT within 60 seconds of launch)
but their solutions were based on Express. I didn't use express for my app.
Is there any other way to not set the port to a fixed number?

It doesn't matter if you use express or not. Herouku binds a port for you in the process.env.PORT environment variable. You need to use that like so:
var port = process.env.PORT || 1337
Then use .listen(port)
Make sure you're connecting to the correct port in your browser (log the port to console to be sure)

Related

Failed to load resource: the server responded with a status of 404 (Not Found) Node.js socket.io

I'm trying to create a server using Node.js and socket.io and it starts perfectly. However, when I'm trying to visit the site of my server through the browser, he writes "Cannot Get /" and in the console gives an error "Failed to Load Resource: The Server Respondd with A Status of 404 (Not Found)". For two days I'm trying to understand where the problem and I will be very grateful to your help. Here is my server code:
const express = require("express");
var http = require("http");
const app = express();
const port = process.env.PORT || 5000;
var server = http.createServer(app);
var io = require("socket.io").listen(server);
//middlewre
app.use(express.json());
io.on("connection", (socket) => {
console.log("connected");
console.log(socket.id, "has joined");
socket.on("/test", (msg) => {
console.log(msg);
})
});
server.listen(port, "0.0.0.0", () => {
console.log("server started");
});
Your server is currently not set up to handle any other http traffic than Websocket connection upgrade requests, which you can not make by entering a url in your browser. Also, the browser is not equipped to negotiate this connection upgrade or to keep the Websocket connection working once established. For this you need some javascript code to run on the client side.
The socket.io library provides everything you need, look at a minimally working example at the link provided below. You should basically just set up your server to serve an html document which provides a context from which the whole websocket connection upgrade can be managed - and the connection maintained - by the socket.io library.
https://socket.io/docs/v2#Minimal-working-example

Node.js with express and websocket giving error during WebSocket handshake: Unexpected response code: 200

So I am trying to set up a website that also has websockets where both the http-server and the websocket listens on the same port:
const WebSocket = require('ws');
var express = require('express');
var app = express();
wss = new WebSocket.Server({server : app});
app.get('/', function(req, res){
res.send('hello world!');
});
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
});
ws.send('some text');
});
app.listen(8080, function(){
console.log('app started');
});
If I then load the servers website in chrome-browser I am greeted with "hello world!". So far so good. But if I open up the webconsole and try to connect with
var exampleSocket = new WebSocket("ws://192.10.10.30:8080");
I get the following errormessage:
WebSocket connection to 'ws://192.10.10.30:8080/' failed: Error
during WebSocket handshake: Unexpected response code: 200
My first thought was, do I have to explicitly declare an http-server ?
But I read this post
Serve WebSocket and HTTP server at same address on Node.js and there was no http-server explicitly declared. Please help me on this.
You're passing an Express app instance as server, which should be an HTTP/HTTPS server instance. Such an instance is returned by app.listen:
var app = express();
var server = app.listen(8080, function(){
console.log('app started');
});
wss = new WebSocket.Server({server : server});
I was having this issue on a Windows machine and discovered the reason was IIS did not have the WebSocket Protocol turned on. Ensure IIS on the machine supports WebSocket:
Control Panel -> Programs and Features -> Turn Windows features on or off.
Expand Internet Information Services, expand World Wide Web Services, expand Application Development Features, and then ensure WebSocket Protocol is checked.

Is there a way to restart node server in runtime?

I am trying to define an endpoint in my express server that whenever this end point is called, the server restarts automatically in runtime.
for example, using express my server would look something like this ...
var express = require('express')
var app = express();
app.post('/restart', (req,res)=>{
//restart or create a new instance of the server
// then reply
res.json({
'message': 'server restarted successfully'
})
})
// =======================
// start the server ======
// =======================
var port = process.env.PORT || 8000;
app.listen(port);
console.log('server running at http://localhost:' + port);
NOTE: Although I am using expressJS, I am open to other solutions like HAPI for example.
Thanks in advance
The only way I know of how to restart a node instance is in the CLI level via npm forever or the pm2, but this is for deployment level xP.
You would need npm module forever to be globally installed on your system and Shelljs as a dependency. Initially start your server as forever start {Path to server.js}. Then you can do
var express = require('express')
var shell = require('shelljs')
var app = express();
app.post('/restart', (req,res)=>{
//restart or create a new instance of the server
shell.exec('forever restart {Path to server.js}');
// then reply
res.json({
'message': 'server restarted successfully'
})
})
// =======================
// start the server ======
// =======================
var port = process.env.PORT || 8000;
app.listen(port);
console.log('server running at http://localhost:' + port);
Also see that you will not get a response as the server would have restarted. You would just get a refused to connect.
You can use PM2 to start, stop your server using simple commands.
Starting an application in production mode is as easy as:
pm2 start app.js
Stop all apps
pm2 stop all
Restart all apps
pm2 restart all
I hope this will work for you.
HTH Thanks!
Since express uses the HTTP from Node, you might initialize the Express server by yourself with the Node HTTP functions, noted here.
Once you have the server started, you might close it and restart it as you wish, as mentioned here.
Just you have to be careful with the already opened connections, as calling the HTTP instance for close will leave the already opened connection(s) still open. More information about closing them all; can be found here.

Why heroku can't run WebSocket server without HTTP server?

I have a WebSocket app on heroku. I tried uploading my WebSocket app without routing http server but it doesn't work. What does mean server routing? And why can't heroku run a WebSocket server without an http server?
And why does it takes express object 'server' as argument in SocketServer
Here's my code of Websocket server.
const express = require('express');
const SocketServer = require('ws').Server;
const path = require('path');
const PORT = process.env.PORT || 3000;
const INDEX = path.join(__dirname, 'index.html');
const server = express()
.use((req, res) => res.sendFile(INDEX) )
.listen(PORT, () => console.log(`Listening on ${ PORT }`));
const wss = new SocketServer({ server });
wss.on("connection",function(ws){
ws.on("message",function(message){
if(message==='exit'){
ws.close();
}else{
wss.clients.forEach(function(client){
client.send(message);
});
console.log(message);
}
});
ws.send("welcome..");
});
There are too many questions in one. I hope my answers will address all of them.
First of all, the websocket protocol is an extension of http, it is not something different. Therefore, a websocket server is necessarily an http server, even though with extended capabilities.
Also, with socket.io, the websockets and http run on the same port. Therefore you have to open the port for http to have your websockets work.
Let's have a look at this line :
const wss = new SocketServer({ server });
It has a syntax error, it must be new SocketServer(server). Also, about the variable name, I would recommend not to use wss for a websocket over http, since wss stands for secure websockets and is related to websockets like http to https.
About routing in heroku: in heroku, you have to define which port your application is using. This can be compared to the firewall on your local machine : if you want to access it from outside, you have to open the port. On heroku, technically it is different to a firewall, but in this point it is similar.

Run NodeJS app on appFog

All I want to do is deploy my little nodeJS app onto the free hosting site, appFog.
Nomatter what ports I set on my client side or on my server side.. I consistently get the error message:
events.js:71
throw arguments[1]; // Unhandled 'error' event
^ Error: listen EADDRINUSE
When this is on my laptop / desktop running on localhost, everything works just fine.
So this is what I've got going on:
Client side:
this.connection = new WebSocket('ws://super1onate.aws.af.cm:1337');
Server Side:
var express = require("express"); // load the express module
var app = express(); // App now holds the server object
// What ports to listen on
app.listen(process.env.VCAP_APP_PORT ||1337);
server.listen(process.env.VCAP_APP_PORT || 1337, function() {
console.log((new Date()) + " Server is listening on port " + webSocketsServerPort); });
Your server code looks ok. What is events.js? It looks like maybe you're including a module that's trying to bind to a port it shouldn't.
Once you get your server running, I don't think your client code will work. As far as I can tell, AppFog doesn't support websockets, and if it does, you'll probably want to hit port 80, not 1337.
Alright, I'm going to answer my own questions.
AppFog does not support WebSockets. websockets =/= socket.io btw fyi
Anyways, according to this site:
http://feedback.appfog.com/forums/171983-appfog/suggestions/3543100-add-websocket-support-to-node-js

Categories

Resources