How to deploy socket io & express server on heroku - node.js

I'm trying to deploy socket io + express server on heroku for a chat application but i am facing a trouble while deploying the server .
First this is my server code
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
users = [];
connections = [];
server.listen(process.env.PORT || 3000);
console.log('Server running...');
io.sockets.on('connection',function(socket){
connections.push(socket);
console.log('Connected %s sockets connected ', connections.length);
//Disconnect
socket.on('disconnect', function(data){
users.splice(users.indexOf(socket.username),1);
connections.splice(connections.indexOf(socket),1);
console.log('Disconneted : %s sockets connected',connections.length);
});
});
This is my package.json file
{
"name": "",
"version": "1.0.0",
"description": "chat application",
"main": "index.js",
"scripts": {
"start": "node index"
},
"author": "",
"license": "ISC",
"dependencies": {
"socket.io": "*",
"express": "*"
}
}
But I'm getting this error
Cannot GET /

Had the same problem (socket.io with express and react).
You can add to server this line:
app.use(express.static('some path to a static file'));
e.g.
app.use(express.static('client/build'))
works for me assuming in package.json has this line at "scripts":
"heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix client"

This error has nothing wrong deployed application. Your app still waits for connection on port 3000 (or port from process.env.PORT). App responds "Cannot GET /" because you don't have any routes.
To see how routes can be implemented look at this -> https://expressjs.com/en/starter/hello-world.html
To see how connect using socket.io (client part) look at this -> https://socket.io/get-started/chat/#Integrating-Socket-IO

Related

How to deploy node app on openshift and run it?

Just created a very simple hello world app using node:
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!');
});
var server_port = process.env.OPENSHIFT_NODEJS_PORT || 8080
var server_ip_address = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1'
app.listen(server_port, server_ip_address, function () {
console.log( "Listening on " + server_ip_address + ", port " + server_port )
});
and it works as it is expected in my local machine,
put that on github and deployed it on openshift, pod created and server running fine:
but when I browse the route which I could find it in Application>>routes menu it says:
Application is not available
The application is currently not serving requests at this endpoint. It may not have been started or is still starting.
I guess I'm using the latest version of openshift since just created an account.
I'm expecting it to show me the Hello world!
update1:
here is my package.json:
{
"name": "npmtest",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node index.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.16.2"
}
}
Your application server IP address needs to be 0.0.0.0. So you either specify an environment variable for that, or hard code it.
have you configure main file in package.json
and maybe you need to get port dynamically from the environment variables check below link for openshift sample
https://github.com/openshift/nodejs-ex

App engine nodejs deployment error

I am trying some hands-on on Google Cloud Platform, App Engine in specific.
For the same, I've created a simple nodejs application which just send Hello Wold message in the response.
But I am unable to access the endpoint and getting the below error
below are my files:
aap.yaml
runtime: nodejs
env: flex
index.js
'use strict';
const http = require('http');
const port = 443;
const requestHandler = (request, response) => {
console.log(request.url);
response.end('Hello Node.js Server!');
}
const server = http.createServer(requestHandler);
server.listen(port, (err) => {
if (err) {
return console.log('something bad happened', err)
}
console.log(`server is listening on ${port}`)
});
package.json
{
"name": "test-pro-for-gcm",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node index.js",
"deploy": "gcloud app deploy",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
UPDATE 1
In the GCP log, 16:31:59.000 server is listening on 443
The port that will receive HTTP requests is 8080.
Use the PORT environment variable in your code to make it compatible with the App Engine environment: const port = process.env.PORT || 443;

node - deploying app to heroku with git

I am trying to deploy my app to heroku and I keep getting this error message saying that it "failed to detect app matching ......." and the push was rejected. I followed the way it said on the heroku website and I keep getting stuck on only that git push heroku master part I have tried doing some research I couldn't find a solution.
{
"name": "home-automation",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server/server.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.15.3",
"johnny-five": "^0.11.3",
"socket.io": "^2.0.3"
}
}
Server.js
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var express = require("express");
var five = require("johnny-five");
var board = new five.Board({port:"COM4"});
const port = process.env.PORT || 3000;
app.use(express.static("public"))
io.on('connection', function (socket) {
console.log("New User Connected")
board.on("ready", function(){
socket.on("turnLightOn", function(data){
var led = new five.Led({
pin:"13"
});
if(data.status){
led.on();
}else{
led.off();
}
})
})
});
server.listen(port, function(){
console.log("Listening on port 3000")
});
index.js
var socket = io();
$("#toggle-light").on("click", function(){
$("#led").toggle();
if($("#led").css("display") == "none"){
var status = false
}else{
var status = true
}
socket.emit("turnLightOn", {
status
})
})
index.html
<html>
<head>
<title>Home Automation</title>
</head>
<body>
<h1>Home Automation</h1>
<button id="toggle-light">Toggle Light</button>
<div id="led" style="width:100px; height:100px; background:yellow;"></div>
<p id="moistureLevel"></p>
<script src="/socket.io/socket.io.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="/js/index.js"></script>
</body>
</html>
This means that a package.json file isn't checked into the root of your git project, so Heroku is detecting that it isn't a Node.js app. You can see this locally:
git show master:package.json
To fix it, you'll want to be sure there is a package.json in the root of your project (where there is also a .git directory), and add it to git:
git add package.json
git commit -m 'track package.json'
The phrasing ('failed to detect set buildpack') could be improved. It should probably say 'failed to detect Node.js app'. When the buildpack's "detect" script is run (https://github.com/heroku/heroku-buildpack-nodejs/blob/master/bin/detect), it looks for a package.json file to verify that there's a node app available to build.

Openshift node app error when restarting

I have a node/socket.io chat app hosted on openshift, and while it starts correctly if i ssh into the server and do "node main.js" (where main.js is the server script that starts the chat), I can't start the app on the server by web interface, where it would go on automatically; If i just start the app by ssh, it would stop working as soon as i exit the terminal.
I get this error when starting the app by the web interface:
Starting Node.js application...
Application is already stopped.
Warning! Could not start Node.js application!
Failed to execute: 'control restart' for /var/lib/openshift/57003fbe7628e1491d00011e/nodejs
In case it's relevant, my package.json file is
{
"name": "rainychat",
"version": "1.0.0",
"description": "rainychat, my chat app",
"main": "main.js",
"dependencies": {
"express": "^4.13.4",
"socket.io": "^1.4.5",
"validator": "^5.1.0"
},
"devDependencies": {},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "JG",
"license": "ISC"
}
And here you can see the files of the app by ftp:
I can't decode what that error means...
My main.js code
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function (req, res) {
res.sendFile(__dirname + '/chat.html'); // /home/redadmin/public_html/rainychat.com
console.log('enviado');
});
app.set('port', process.env.OPENSHIFT_NODEJS_PORT || 8080);
app.set('ip', process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1');
http.listen(app.get('port'), app.get('ip'), function () {
console.log('Listening on port ' + app.get('port'));
});
//... More code
If you're creating a new Node project, start with npm init to create the package.json file. You can add the --auto option to give it safe defaults.
Remember, the JSON file must be valid JSON, so test it with jsonlint or a tool like an online validator.
Any dependencies your project has should be spelled out in the package file. This is done automatically with things like npm install express --save.

Newer socket.io client not connecting to older socket.io server

I'm trying to get a newer socket.io client to connect to a server process that is using an older version of socket.io, 0.9.14. I've included a small example of both client and server to demonstrate this. I know the easy answer is to upgrade the server to a newer socket.io version and that is being done. But that will take some time and I'd like to see if there is something that I can do to make the client communicate successfully with the server without upgrading the server. Ultimately I want an Android client to be able to connect but it's exhibiting similar connect issue as the simple nodejs client sample I've posted here. I don't know it's identical but seems worthwhile to start with nodejs client for testing.
When the client connects it sees "connect sent", "finished emit", but doesn't get the server response message. The server repeatedly shows the following message: "info - unhandled socket.io url". This is repeated until the client is stopped. If I update the server's package.json to use "1.3.5" for socket.io then the example works fine.
Client package.json
{
"name": "ClientJS",
"version": "0.0.0",
"description": "",
"main": "client.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "BSD-2-Clause",
"dependencies": {
"http": "0.0.0",
"socket.io": "1.3.5",
"socket.io-client": "1.3.5"
}
}
client.js
var io = require('socket.io-client');
var serverUrl = 'http://localhost:3300';
var conn = io.connect(serverUrl);
console.log('connect sent');
conn.emit('join', 'default', function(resp, data) {
console.log('server sent resp ' + resp + " " + data);
});
console.log('finished emit: join');
server package.json
{
"name": "ServerJS",
"version": "0.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
},
"author": "",
"license": "BSD-2-Clause",
"dependencies": {
"express": "~4.12.3",
"http": "0.0.0",
"socket.io": "0.9.14"
}
}
server.js
var express = require('express');
var app = express();
var server = require('http').createServer(app);
server.listen(3300);
var io = require('socket.io').listen(server, function() {
console.log('listen callback was called');
});
io.sockets.on('connection', function(socket) {
console.log('connection: event came in');
socket.on('join', function(p1, fn) {
console.log('client sent '+p1);
fn(0, 'some data');
});
});
As I mentioned my real goal is to get an Android client running against this server. But I'm using a Nodejs client to make it easy to demonstrate the problem. Does anyone know how to make this work that doesn't involve upgrading the server side to a newer socket.io? Thanks.

Resources