NodeJS, WebSockets(ws) an Openshift - javascript

I'm trying to create a simple websocket app with NodeJS, WS and Openshift
This is my code:
package.json:
{
"name": "OpenShift-Sample-App",
"version": "1.0.0",
"description": "OpenShift Sample Application",
"keywords": [
"OpenShift",
"Node.js",
"application",
"openshift"
],
"author": {
"name": "John Smith",
"email": "example123#example.com",
"url": "http://www.google.com"
},
"homepage": "http://www.openshift.com/",
"repository": {
"type": "git",
"url": "https://github.com/openshift/origin-server"
},
"engines": {
"node": ">= 0.6.0",
"npm": ">= 1.0.0"
},
"dependencies": {
"express": "^4.12.3",
"socket.io" : "0.9.16",
"ws" : "0.4.31"
},
"devDependencies": {},
"bundleDependencies": [],
"private": true,
"main": "server.js"
}
app.js:
#!/bin/env node
// OpenShift sample Node application
var express = require('express');
var fs = require('fs');
var WebSocketServer = require('ws').Server;
var SampleApp = function () {
// Scope.
var self = this;
var url = '127.0.0.1:27017/' + process.env.OPENSHIFT_APP_NAME;
self.setupVariables = function () {
// Set the environment variables we need.
self.ipaddress = process.env.OPENSHIFT_NODEJS_IP;
self.port = process.env.OPENSHIFT_NODEJS_PORT || 8080;
if (typeof self.ipaddress === "undefined") {
// Log errors on OpenShift but continue w/ 127.0.0.1 - this
// allows us to run/test the app locally.
console.warn('No OPENSHIFT_NODEJS_IP var, using 127.0.0.1');
self.ipaddress = "127.0.0.1";
}
;
};
self.populateCache = function () {
if (typeof self.zcache === "undefined") {
self.zcache = {'index.html': ''};
}
// Local cache for static content.
self.zcache['index.html'] = fs.readFileSync('./index.html');
};
self.cache_get = function (key) {
return self.zcache[key];
};
self.terminator = function (sig) {
if (typeof sig === "string") {
console.log('%s: Received %s - terminating sample app ...',
Date(Date.now()), sig);
process.exit(1);
}
console.log('%s: Node server stopped.', Date(Date.now()));
};
self.setupTerminationHandlers = function () {
// Process on exit and signals.
process.on('exit', function () {
self.terminator();
});
// Removed 'SIGPIPE' from the list - bugz 852598.
['SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT',
'SIGBUS', 'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGUSR2', 'SIGTERM'
].forEach(function (element, index, array) {
process.on(element, function () {
self.terminator(element);
});
});
};
self.createGetRoutes = function () {
self.getRoutes = {};
self.getRoutes['/'] = function (req, res) {
res.setHeader('Content-Type', 'text/html');
res.send(self.cache_get('index.html'));
};
};
self.initializeServer = function () {
self.createGetRoutes();
self.app = express();
// Add handlers for the app (from the routes).
for (var r in self.getRoutes) {
self.app.get(r, self.getRoutes[r]);
}
}
self.initialize = function () {
self.setupVariables();
self.populateCache();
self.setupTerminationHandlers();
// Create the express server and routes.
self.initializeServer();
};
self.start = function () {
var wss = new WebSocketServer({ server: self.app
})
wss.on('connection', function connection(ws) {
console.log(".....Connected");
var location = url.parse(ws.upgradeReq.url, true);
ws.on('message', function incoming(message) {
console.log('received: %s', message);
});
ws.send('something');
});
self.app.listen(self.port, self.ipaddress, function () {
console.log('%s: Node server started on %s:%d ...',
Date(Date.now()), self.ipaddress, self.port);
});
};
};
var zapp = new SampleApp();
zapp.initialize();
zapp.start();
when I run:
wscat --connect ws://something.rhcloud.com:8000
I got:
connected (press CTRL+C to quit)
disconnected
What is wrong in the source code?
Thanks

Within (pre-docker) OpenShift, your application connects to the system load balancer by listening on process.env.OPENSHIFT_NODEJS_PORT.
OpenShift's load balancer then exposes your application externally on four different ports:
80 - basic http connections available
443 - basic https connections available
8080 - http and ws connections available
8443 - https and ws connections available
Unfortunately, in the pre-docker versions of OpenShift, the ws connection upgrade (from http or https) will only work correctly on ports 8080 and 8443.
You can work around this issue by including a client-side check to test if the server hostname includes the string "rhcloud.com". If it does, you'll need to establish your client's socket connection using the alternate port number.
Newer, docker-based releases of OpenShift include full websocket support on standard web ports.

Related

Socket.io Not listening event on client side

I am using official code example of socket.io and trying to understand about how it works.
event is triggering and receiving on server side but client side not listening on that event.
Server i am running on node.js port 3000 and
client i am running on VSCode GoLive Extension on port 5500
Here is my detailed code
Package.json
{
"name": "socket-chat-example",
"version": "0.0.1",
"description": "my first socket.io app",
"dependencies": {
"cors": "^2.8.5",
"express": "^4.17.1",
"socket.io": "^4.1.2"
},
"scripts": {
"start": "DEBUG=* nodemon index.js"
},
"devDependencies": {
"nodemon": "^2.0.15"
}
}
Index.html (Due to Stackoverflow restrictions i am unable to paste whole page code Here is only body code without css)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.socket.io/4.4.1/socket.io.min.js"></script>
<ul id="messages"></ul>
<div id="form">
<input id="input" autocomplete="off" />
<button id="btn_submit">Send</button>
</div>
<script>
$(function () {
var socket = io("http://localhost:3000");
socket.on("connect", function () {
console.log("client is connected", socket.connected);
socket.emit("message", "Welcome To Chat");
});
var messages = document.getElementById("messages");
var input = document.getElementById("input");
$("#btn_submit").on("click", function () {
if (input.value) {
console.log(input.value);
socket.emit("message", input.value, (response) => {
console.log(response); // "got it"
});
input.value = "";
}
});
console.log(socket);
socket.on("message", function (msg) {
console.log(msg);
var item = document.createElement("li");
item.textContent = msg;
messages.appendChild(item);
window.scrollTo(0, document.body.scrollHeight);
});
});
</script>
index.js
const app = require('express')();
var cors = require('cors');
const http = require('http').Server(app);
const io = require('socket.io')(http, {
cors: {
origin: "*",
methods: ["GET", "POST"]
}
});
const port = process.env.PORT || 3000;
app.use(cors())
const connections = [];
io.on('connection', (socket) => {
connections.push(socket);
console.log(" %s sockets is connected", connections.length);
socket.on("disconnect", () => {
connections.splice(connections.indexOf(socket), 1);
console.log("Now %s sockets is connected", connections.length);
});
});
http.listen(port, () => {
console.log(`Socket.IO server running at http://localhost:${port}/`);
});
In your index.js file you've initialized the socket but I can't see any event receiving or emitting method.
You should use socket.emit() in server side to send the data to client and socket.on() to receive the data from client. You should send socket.emit("message", "Message") from index.js file.
You can find better explanation here.

Deploying botkit framework to azure and testing in the webchat returns 502

For my internship I am making a chatbot. I created a bot using botkit framework (yo botkit) and got as far as using it in the ms Teams client. But only using my localhost + ngrok setup. when I want to use https://{myproject}.azurewebsites.net/api/messages after deployment I get a 502 error message.
To try if I actually did my deployment okay, I made another project using "yo botbuilder" without botkit framework. Following the same steps I deployed it to a fresh Group. This time using the https://{myproject}.azurewebsites.net/api/messages url worked. (standard echo bot)
After that, I copied my bot files from my first project into my new one and replaced my index.js from my standard botbuilder project with my bot.js file from my botkit framework project.
I just used the standard botbuilder -> index.js file and botkit -> bot.js file +
in my package.json I changed the main and the scripts to point to bot.js instead of index.js.
After deploying, it just gave me my 502 again.
index.js
const dotenv = require('dotenv');
const path = require('path');
const restify = require('restify');
// Import required bot services.
// See https://aka.ms/bot-services to learn more about the different parts of a bot.
const { BotFrameworkAdapter } = require('botbuilder');
// This bot's main dialog.
const { EchoBot } = require('./bot');
// Import required bot configuration.
const ENV_FILE = path.join(__dirname, '.env');
dotenv.config({ path: ENV_FILE });
// Create HTTP server
const server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, () => {
console.log(`\n${ server.name } listening to ${ server.url }`);
console.log('\nGet Bot Framework Emulator: https://aka.ms/botframework-emulator');
console.log('\nTo talk to your bot, open the emulator select "Open Bot"');
});
// Create adapter.
// See https://aka.ms/about-bot-adapter to learn more about how bots work.
const adapter = new BotFrameworkAdapter({
appId: process.env.MicrosoftAppId,
appPassword: process.env.MicrosoftAppPassword
});
// Catch-all for errors.
const onTurnErrorHandler = async (context, error) => {
// This check writes out errors to console log .vs. app insights.
// NOTE: In production environment, you should consider logging this to Azure
// application insights.
console.error(`\n [onTurnError] unhandled error: ${ error }`);
// Send a trace activity, which will be displayed in Bot Framework Emulator
await context.sendTraceActivity(
'OnTurnError Trace',
`${ error }`,
'https://www.botframework.com/schemas/error',
'TurnError'
);
// Send a message to the user
await context.sendActivity('The bot encountered an error or bug.');
await context.sendActivity('To continue to run this bot, please fix the bot source code.');
};
// Set the onTurnError for the singleton BotFrameworkAdapter.
adapter.onTurnError = onTurnErrorHandler;
// Create the main dialog.
const myBot = new EchoBot();
// Listen for incoming requests.
server.post('/api/messages', (req, res) => {
adapter.processActivity(req, res, async (context) => {
// Route to main dialog.
await myBot.run(context);
});
});
// Listen for Upgrade requests for Streaming.
server.on('upgrade', (req, socket, head) => {
// Create an adapter scoped to this WebSocket connection to allow storing session data.
const streamingAdapter = new BotFrameworkAdapter({
appId: process.env.MicrosoftAppId,
appPassword: process.env.MicrosoftAppPassword
});
// Set onTurnError for the BotFrameworkAdapter created for each connection.
streamingAdapter.onTurnError = onTurnErrorHandler;
streamingAdapter.useWebSocket(req, socket, head, async (context) => {
// After connecting via WebSocket, run this logic for every request sent over
// the WebSocket connection.
await myBot.run(context);
});
});
bot.js
const { Botkit } = require('botkit');
const { BotkitCMSHelper } = require('botkit-plugin-cms');
// Import a platform-specific adapter for botframework.
const { MongoDbStorage } = require('botbuilder-storage-mongodb');
// Load process.env values from .env file
require('dotenv').config();
let storage = null;
if (process.env.MONGO_URI) {
storage = mongoStorage = new MongoDbStorage({
url : process.env.MONGO_URI,
});
}
const controller = new Botkit({
webhook_uri: '/api/messages',
adapterConfig: {
appId: process.env.APP_ID,
appPassword: process.env.APP_PASSWORD,
},
storage
});
if (process.env.CMS_URI) {
controller.usePlugin(new BotkitCMSHelper({
uri: process.env.CMS_URI,
token: process.env.CMS_TOKEN,
}));
}
// Once the bot has booted up its internal services, you can use them to do stuff.
controller.ready(() => {
// load traditional developer-created local custom feature modules
controller.loadModules(__dirname + '/features');
/* catch-all that uses the CMS to trigger dialogs */
if (controller.plugins.cms) {
controller.on('message,direct_message', async (bot, message) => {
let results = false;
results = await controller.plugins.cms.testTrigger(bot, message);
if (results !== false) {
// do not continue middleware!
return false;
}
});
}
});
controller.webserver.get('/', (req, res) => {
res.send(`This app is running Botkit ${ controller.version }.`);
});
package.json
{
"name": "my-chat-bot",
"version": "1.0.0",
"description": "Demonstrate the core capabilities of the Microsoft Bot Framework",
"author": "Generated using Microsoft Bot Builder Yeoman generator v4.7.0",
"license": "MIT",
"main": "bot.js",
"scripts": {
"start": "node ./bot.js",
"watch": "nodemon ./bot.js",
"lint": "eslint .",
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "https://github.com"
},
"dependencies": {
"botbuilder": "~4.7.0",
"dotenv": "^8.2.0",
"restify": "~8.4.0",
"botbuilder-storage-mongodb": "^0.9.5",
"botkit": "^4.6.2",
"botkit-plugin-cms": "^1.0.3",
"firebase-admin": "^8.9.2",
"jira-client": "^6.15.0",
"request": "^2.88.2"
},
"devDependencies": {
"eslint": "^6.6.0",
"eslint-config-standard": "^14.1.0",
"eslint-plugin-import": "^2.18.2",
"eslint-plugin-node": "^10.0.0",
"eslint-plugin-promise": "^4.2.1",
"eslint-plugin-standard": "^4.0.1",
"nodemon": "~1.19.4"
}
}

Can't deploy simple node.js app to heroku nor MongoDB

So im trying to deploy a simple twitter like app to HEROKU or MongoDB and i'm currently nailing either. For mongodb I get one out of two outcomes, either a internal server error or the actual code displaying on the browser instead of the app. Since I have two separate folders for each implementation i'm going to post subsequently.
MONGODB
Index.js (This is the server side node code)
const express = require('express');
//Cors permite que cualquiera se comunique con el server.
const cors = require('cors');
const monk = require('monk');
const Filter = require('bad-words');
const rateLimit = require('express-rate-limit');
const filter = new Filter();
const app = express();
const db = monk(process.env.MONGO_URI || 'localhost/meower');
const mews = db.get('mews');
//ORDER MATTERS, WHAT IS FIRST GETS EXECUTED FIRST
app.enable('trust proxy');
app.use(cors());
//any incoming request that is JSON will pass
app.use(express.json());
//server, when you get a request run this function.
app.get('/',(request,response) => {
res.json({
message: 'Meower!'
});
});
app.get('/mews', (req,res) => {
mews
.find()
.then(mews => {
res.json(mews);
});
});
function isvalidmew(mew){
return mew.name && mew.name.toString().trim() !== '' &&
mew.content && mew.content.toString().trim() !== '';
}
//limit the submit rate
app.use(rateLimit({
windowMs: 30 * 1000,
max: 2
}));
//this will wait for incoming data and insert in database
app.post('/mews', (req,res) => {
if(isvalidmew(req.body)){
const mew = {
name: filter.clean(req.body.name.toString()),
content: filter.clean(req.body.content.toString()),
created: new Date()
};
mews
.insert(mew)
.then(createdMew => {
res.json(createdMew);
});
} else {
res.status(422);
res.json({
message:'Hey! Name and Content are required!'
});
}
});
//abre el server en el puerto 5000
app.listen(5000, () => {
console.log('Listening on http://localhost:5000');
});
Client.js
const form = document.querySelector('form');
const loadingElement = document.querySelector('.loading');
const mewsElement = document.querySelector('.mews');
const API_URL = 'http://localhost:5000/mews';
loadingElement.style.display = '';
console.log('hola')
listallmews();
form.addEventListener('submit', (event) => {
event.preventDefault();
const formData = new FormData(form);
//We grab the stuff from the form
const name = formData.get('name');
const content = formData.get('content');
//We put it in an object
const mew = {
name,
content
};
//We send the data to the server
form.style.display = 'none';
loadingElement.style.display = '';
fetch(API_URL, {
method: 'POST',
body: JSON.stringify(mew),
headers : {
'content-type':'application/json'
}
}).then(response => response.json())
.then(createdMew => {
form.reset();
setTimeout(() => {
form.style.display = '';
},30000);
listallmews();
});
});
function listallmews(){
mewsElement.innerHTML = '';
fetch(API_URL)
.then(response => response.json())
.then(mews => {
console.log(mews);
mews.reverse();
mews.forEach(mew =>{
const div = document.createElement('div');
const header = document.createElement('h3');
header.textContent= mew.name
const contents = document.createElement('p')
contents.textContent= mew.content;
const date = document.createElement('small');
date.textContent = new Date(mew.created);
div.appendChild(header);
div.appendChild(contents);
div.appendChild(date);
mewsElement.appendChild(div);
});
loadingElement.style.display = 'none'
});
}
now.json
{
"name": "camitter-api",
"version": 2,
"builds": [
{
"src": "index.js",
"use": "#now/node-server"
}
],
"routes": [
{ "src": "/.*", "dest": "index.js" }
],
"env": {
"MONGO_URI": "#camitter-db"
}
}
and package.json
{
"name": "server",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node index.js",
"dev": "nodemon index.js"
},
"keywords": [],
"author": "CJ R. <cj#null.computer> (https://w3cj.now.sh)",
"license": "MIT",
"dependencies": {
"bad-words": "^1.6.3",
"cors": "^2.8.4",
"express": "^4.16.3",
"express-rate-limit": "^3.1.1",
"monk": "^6.0.6",
"morgan": "^1.9.1"
},
"devDependencies": {
"nodemon": "^1.18.4"
}
}
And this is the terminal output on implementation. Currently the link shows "internal server error"
Alejandro#DESKTOP-LOJH5G7 MINGW64 ~/Desktop/Programacion/Meower
$ now secrets add camisite mongodb+srv://alenieto:myactualpassword#camisite-irtu2.mongodb.net/test?retryWrites=true&w=majority
[1] 444
Alejandro#DESKTOP-LOJH5G7 MINGW64 ~/Desktop/Programacion/Meower
$ Now CLI 18.0.0
Success! Secret camisite added under alenieto97 [709ms]
$ now -e MONGO_URI=#camisite
Now CLI 18.0.0
? Set up and deploy “~\Desktop\Programacion\Meower”? [Y/n] y
? Which scope do you want to deploy to? Alejandro Nieto
? Found project “alenieto97/meower”. Link to it? [Y/n] n
? Link to different existing project? [Y/n] n
? What’s your project’s name? camisite
? In which directory is your code located? ./
No framework detected. Default project settings:
- Build Command: `npm run now-build` or `npm run build`
- Output Directory: `public` if it exists, or `.`
� Inspect: https://zeit.co/alenieto97/camisite/ei55o9z4q [2s]
✅ Production: https://camisite.now.sh [copied to clipboard] [5s]
� Deployed to production. Run `now --prod` to overwrite later (https://zeit.ink/2F).
� To change the domain or build command, go to https://zeit.co/alenieto97/camisite/settings
[1]+ Done now secrets add camisite mongodb+srv://alenieto:lapata97#camisite-irtu2.mongodb.net/test?retryWrites=true
Alejandro#DESKTOP-LOJH5G7 MINGW64 ~/Desktop/Programacion/Meower
$ cd server
Alejandro#DESKTOP-LOJH5G7 MINGW64 ~/Desktop/Programacion/Meower/server
$ now -e MONGO_URI=#camisite
Now CLI 18.0.0
❗️ The `name` property in now.json is deprecated (https://zeit.ink/5F)
� Inspect: https://zeit.co/alenieto97/camitter/6b76zrggu [3s]
✅ Preview: https://camitter.alenieto97.now.sh [copied to clipboard] [20s]
� To deploy to production (camitter.now.sh), run `now --prod`
❗️ Zero-configuration deployments are recommended instead of a `builds` property in `now.json`. The "Build and Development Settings" in your Project will not apply.
Alejandro#DESKTOP-LOJH5G7 MINGW64 ~/Desktop/Programacion/Meower/server
HEROKU
Here i'm pretty sure im doing something wrong on the index.js or client.js or both. I saw tons of guides and have all the files necesary. When I deploy, the app simply doesn't work. Since I actually tried to adapt the code to work on Heroku I'm pretty sure the problem lies in the code itself. This is The folder:
node_modules
.gitignore
index.js
package_lock.json
client.js
favicon.ico
index.html
loading.gif
styles.css
Procfile
Index.js
const express = require('express');
//Cors permite que cualquiera se comunique con el server.
const cors = require('cors');
const Filter = require('bad-words');
const rateLimit = require('express-rate-limit');
const { Pool, Client } = require('pg');
const port = process.env.PORT;
const connectionString = 'postgres://gvvsunuvtdhxpq:e9d3239ab17ea6f38d0b6303dee62b7704b37574e5eb2783ca7edb868cc7192a#ec2-18-235-20-228.compute-1.amazonaws.com:5432/d7df9kofqifk5b'
const pool = new Pool({
connectionString: connectionString,
})
const filter = new Filter();
const app = express();
//ORDER MATTERS, WHAT IS FIRST GETS EXECUTED FIRST
app.enable('trust proxy');
app.use(cors());
//any incoming request that is JSON will pass
app.use(express.json());
//server, when you get a request run this function.
app.get('/',(request,response) => {
res.json({
message: 'Meower!'
});
});
app.get('/mews', async (req, res) => {
try {
const client = await pool.connect()
const result = await client.query('SELECT * FROM test_table');
const results = { 'results': (result) ? result.rows : null};
res.render('pages/mews', results );
client.release();
} catch (err) {
console.error(err);
res.send("Error " + err);
}
})
function isvalidmew(mew){
return mew.name && mew.name.toString().trim() !== '' &&
mew.content && mew.content.toString().trim() !== '';
}
//limit the submit rate
app.use(rateLimit({
windowMs: 30 * 1000,
max: 2
}));
//this will wait for incoming data and insert in database
app.post('/mews', (req,res) => {
if(isvalidmew(req.body)){
const mew = {
name: filter.clean(req.body.name.toString()),
content: filter.clean(req.body.content.toString()),
created: new Date()
};
mews
.insert(mew)
.then(createdMew => {
res.json(createdMew);
});
} else {
res.status(422);
res.json({
message:'Hey! Name and Content are required!'
});
}
});
app.listen(port, () => {
console.log('Listening on PORT');
});
Client.js
const form = document.querySelector('form');
const loadingElement = document.querySelector('.loading');
const mewsElement = document.querySelector('.mews');
const API_URL = 'https://camisite.herokuapp.com/mews';
loadingElement.style.display = '';
listallmews();
form.addEventListener('submit', (event) => {
event.preventDefault();
const formData = new FormData(form);
//We grab the stuff from the form
const name = formData.get('name');
const content = formData.get('content');
//We put it in an object
const mew = {
name,
content
};
//We send the data to the server
form.style.display = 'none';
loadingElement.style.display = '';
fetch(API_URL, {
method: 'POST',
body: JSON.stringify(mew),
headers : {
'content-type':'application/json'
}
}).then(response => response.json())
.then(createdMew => {
form.reset();
setTimeout(() => {
form.style.display = '';
},30000);
listallmews();
});
});
function listallmews(){
mewsElement.innerHTML = '';
fetch(API_URL)
.then(response => response.json())
.then(mews => {
console.log(mews);
mews.reverse();
mews.forEach(mew =>{
const div = document.createElement('div');
const header = document.createElement('h3');
header.textContent= mew.name
const contents = document.createElement('p')
contents.textContent= mew.content;
const date = document.createElement('small');
date.textContent = new Date(mew.created);
div.appendChild(header);
div.appendChild(contents);
div.appendChild(date);
mewsElement.appendChild(div);
});
loadingElement.style.display = 'none'
});
}
Procfile
web: node index.js
Package.json
{
"name": "server",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node index.js",
"dev": "nodemon index.js"
},
"keywords": [],
"author": "CJ R. <cj#null.computer> (https://w3cj.now.sh)",
"license": "MIT",
"dependencies": {
"bad-words": "^1.6.3",
"cors": "^2.8.5",
"express": "^4.16.3",
"express-rate-limit": "^3.1.1",
"monk": "^6.0.6",
"morgan": "^1.9.1",
"pg": "^7.18.2"
},
"devDependencies": {
"nodemon": "^1.18.4"
}
}
I appreciate a lot any help to deploy on any of the two platforms, im trying to make the most out of this quarantine and have been trying to solve this for twenty hours straight. Cheers to any isolated folks!
Change index.js file
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Our app is running on port ${ PORT }`);
});
You can also refer https://help.heroku.com/P1AVPANS/why-is-my-node-js-app-crashing-with-an-r10-error

ReferenceError: process is not defined, Error in heroku app with node and sockets.io

Just deployed an app (https://socket-draw-app.herokuapp.com/) on Heroku but am getting this error: ReferenceError: process is not defined. in a javascript file: sketch.js. I am using the p5.js library. Code below (firstly the sketch.js and then my server.js node file) :
var socket;
function setup() {
createCanvas(400, 400);
background(0);
socket = io.connect(process.env.PORT || 3000);
socket.on('mouse',
function(data) {
console.log("Got: " + data.x + " " + data.y);
fill(0,0,255);
noStroke();
ellipse(data.x, data.y, 20, 20);
}
);
}
function draw() {
// Nothing
}
function mouseDragged() {
// Draw some white circles
fill(255);
noStroke();
ellipse(mouseX,mouseY,20,20);
// Send the mouse coordinates
sendmouse(mouseX,mouseY);
}
// Function for sending to the socket
function sendmouse(xpos, ypos) {
// We are sending!
console.log("sendmouse: " + xpos + " " + ypos);
// Make a little object with and y
var data = {
x: xpos,
y: ypos
};
// Send that object to the socket
socket.emit('mouse',data);
}
var express = require('express');
// Create the app
var app = express();
// Set up the server
// process.env.PORT is related to deploying on heroku
var server = app.listen(process.env.PORT || 3000, listen);
// This call back just tells us that the server has started
function listen() {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://' + host + ':' + port);
}
app.use(express.static('public'));
// WebSocket Portion
// WebSockets work with the HTTP server
var io = require('socket.io')(server);
// Register a callback function to run when we have an individual connection
// This is run for each individual user that connects
io.sockets.on('connection',
// We are given a websocket object in our function
function (socket) {
console.log("We have a new client: " + socket.id);
// When this user emits, client side: socket.emit('otherevent',some data);
socket.on('mouse',
function(data) {
// Data comes in as whatever was sent, including objects
console.log("Received: 'mouse' " + data.x + " " + data.y);
// Send it to all other clients
socket.broadcast.emit('mouse', data);
// This is a way to send to everyone including sender
// io.sockets.emit('message', "this goes to everyone");
}
);
socket.on('disconnect', function() {
console.log("Client has disconnected");
});
}
);
{
"name": "sockets_p5",
"version": "1.0.0",
"description": "This is an example for how to use sockets with p5.js.",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Daniel Shiffman",
"license": "ISC",
"dependencies": {
"express": "^4.16.2",
"socket.io": "^1.4.5"
}
}
Was deployed from my machine running Ubuntu 16.04. Node version 4.2.6 and Npm version 3.5.2 .

Can't create a node.js webserver using Openshift. Object #<Object> has no method 'listen'

I'm trying to deploy a simple node.js app on Openshift but I simply can't get it to run. My package.json is:
{
"name": "songcatapp",
"version": "1.0.0",
"engines": {
"node": ">= 0.6.0",
"npm": ">= 1.0.0"
},
"dependencies": {
"colors": "0.x.x",
"optimist": "0.2.x",
"pkginfo": "0.2.x",
"http-proxy": "0.7.3",
"htmlparser": "1.7.3",
"mongodb": "0.9.7-0",
"ent": "0.x.x"
},
"devDependencies": {},
"bundleDependencies": [],
"private": true,
"scripts": {
"start": "node server.js"
},
"main": "server.js"
}
My server.js is:
var server_port = process.env.OPENSHIFT_NODEJS_PORT || 8080
var server_ip_address = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1'
console.log("ServerPort: "+server_port+", ServerIP: "+server_ip_address);
http.createServer(function(request, response) {
response.writeHead(200);
response.end('Hello Http');
});
console.log("http: %j", http);
http.listen(server_port, server_ip_address, function () {
console.log( "Listening on " + server_ip_address + ", server_port " + port )
});
On application startup, the error I get is:
http.listen(server_port, server_ip_address, function () {
^
TypeError: Object #<Object> has no method 'listen'
at Object.<anonymous> (/var/lib/openshift/53520a0be0b8cd914a000187/app-root/runtime/repo/server.js:578:6)
I have deployed the application both on DotCloud and Amazon without any problems. I have been stuck on Openshift for a couple of days now!
Can anyone please help?
Many Thanks
http.createServer() creates and returns a server instance object, that instance is what has the server methods such as listen():
var server = http.createServer(function(request, response) {
response.writeHead(200);
response.end('Hello Http');
});
server.listen(server_port, server_ip_address, function () {
console.log( "Listening on " + server_ip_address + ", server_port " + port )
});
It doesn't look like you've loaded the http module.
Also, I think you want to create a server, and then call server.listen, or maybe chain the two statements together, like this:
var http = require('http')
var server_port = process.env.OPENSHIFT_NODEJS_PORT || 8080
var server_ip_address = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1'
http.createServer(function(request, response) {
response.writeHead(200);
response.end('Hello Http');
}).listen(server_port, server_ip_address, function () {
console.log( "Listening on " + server_ip_address + ", server_port " + server_port )
});
Does your code run locally with "npm install" followed by "npm start"?

Categories

Resources