Middleware error in geting handshake session Node.js - javascript

I am having problems with Middleware to get the handshake.session in socket.io module to work properly with even a simple example.
1.- I have some error in the cod
how can be solved
2.- please just need
get handshake session
Thanks
I am just trying to get this example to work:
const KEY = 'express.sid'
, SECRET = 'express';
var express = require('express'), app = express()
, server = require('http').createServer(app)
, io = require('socket.io').listen(server)
, cookie = express.cookieParser(SECRET)
, store = new express.session.MemoryStore()
, session = express.session({secret: SECRET, key: KEY, store: store});
app.configure(function(){
app.set('view engine', 'ejs');
app.use(cookie);
app.use(session);
});
app.get("/", function(req, res){req.session.ID = "U"+2;});
server.listen(3000);
io.set('authorization', function(data, accept) {
cookie(data, {}, function(err) {
if (!err) {
var sessionID = data.signedCookies[KEY];
store.get(sessionID, function(err, session) {
if (err || !session) {
accept(null, false);
} else {
data.session = session;
accept(null, true);
}
});
} else {
accept(null, false);
}
});
});
io.sockets.on('connection', function (socket) {
var session = socket.handshake.session, id = session.ID;
console.log(id);
});

Related

Pass sockets.io from express server file to route file

I would use sockets in a separate route file .
I'm using the method mentioned in this answer : Express 4 Routes Using Socket.io
I have copied exactly the same logic. In server file :
var http = require("http");
var admin = require('firebase-admin');
var firebase = require("firebase");
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var port = process.env.app_port || 8080; // set our port
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
var server = app.listen(port);
var io = require("socket.io")(server);
var routerProj = require("./routes/routes")(io);
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT ,DELETE');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept,*");
next();
});
var config = {
.... DB Configuration ....
};
firebase.initializeApp(config);
var serviceAccount = require("./ServiceAcountKey.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://datatable-18f93.firebaseio.com"
});
io.on("connection", function (client) {
console.log("Un client est connecté !");
//routerProj(client);
});
app.use("/v1", routerProj, function (req) {
//Create HTTP server and listen on port 8000 for requests
});
My connection socket is working and the console.log runs in terminal
routes.js file
var express = require("express"); // call express
var router = express.Router(); // get an instance of the express Router
var admin = require("firebase-admin");
var returnRouter = function (client) {
router.use(function (req, res, next) {
// do logging
client.on('save-message', function (socket) { console.log("heheyy") })
});
router
.route("/")
.get(function (req, res, err) {
// Get a database reference to our posts
var db = admin.database();
var ref = db.ref("/");
// Attach an asynchronous callback to read the data at our posts reference
ref.once("value", function (snapshot) {
var list = [];
snapshot.forEach(function (elem) {
list.push(elem.val());
})
list = JSON.stringify(list);
//list = JSON.parse(list)
console.log(err);
//console.log(JSON.stringify(list))
res.send(list);
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
res.status(500).send(errorObject.code);
});
});
router
.route("/")
.post(function (req, res, err) {
console.log(req.body);
// Get a database reference to our posts
var db = admin.database();
var ref = db.ref("/");
ref.push(
{
"text": req.body.text
}
);
});
return router;
}
module.exports = returnRouter;
save-message is emit in Angular when my arr is running :
ngOnInit() {
this.socket.emit('save-message', { room: "hello" });
}
Save-message event is not getting read neither the routes file, In my angular application services does not get data from routes. and console.log in get and post routes does not work.
My question is how to get sockets working in a reparate file ?
You should move the socket.io listener outside of the express use route. It's not really clear why you would want it there as it will register a new listener every time someone makes a request to your v1 endpoint.
You likely aren't seeing the messages because the listener does not register until someone makes a request to the v1 endpoint and the client already sent its message.
var returnRouter = function (client) {
// do logging
client.on('save-message', function (socket) {
console.log("heheyy");
});
...
};

Node.js : get cloudant variable form app.js file

I have the node js application on bluemix. I want to use the cloudant variable on app js from provider js.But it does not work. Please help me review it
app.js
/**
* Module dependencies.
*/
var express = require('express'),
routes = require('./routes'),
user = require('./routes/user'),
http = require('http'),
path = require('path'),
fs = require('fs'),
ibmbluemix = require('ibmbluemix'),
ibmpush = require('ibmpush');
var app = express();
var db;
var cloudant;
var fileToUpload;
var dbCredentials = {
dbName : 'my_sample_db',
dbProvider : 'provider'
};
var config = {
// change to real application route assigned for your application
applicationRoute : "http://demo.mybluemix.net"
//for test by postman.
};
// init core sdk
ibmbluemix.initialize(config);
var ibmconfig = ibmbluemix.getConfig();
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var logger = require('morgan');
var errorHandler = require('errorhandler');
var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
app.use(logger('dev'));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(methodOverride());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/style', express.static(path.join(__dirname, '/views/style')));
//CORS middleware
var allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-type,Accept,X-Access-Token,X-Key,IBM-APPLICATION-SECRET,IBM-APPLICATION-ID,IBM-DEVICE-MODEL,IBM-DEVICE-TYPE,IBM-DEVICE-ID,IBM-DEVICE-PLATFORM-VERSION, IBM-DEVICE-NAME,IBM-REQUEST-CORRELATION-ID,X-REWRITE-DOMAIN');
next();
};
app.use(allowCrossDomain);
// development only
if ('development' == app.get('env')) {
app.use(errorHandler());
}
function initDBConnection() {
if(process.env.VCAP_SERVICES) {
var vcapServices = JSON.parse(process.env.VCAP_SERVICES);
// Pattern match to find the first instance of a Cloudant service in
// VCAP_SERVICES. If you know your service key, you can access the
// service credentials directly by using the vcapServices object.
for(var vcapService in vcapServices){
if(vcapService.match(/cloudant/i)){
dbCredentials.host = vcapServices[vcapService][0].credentials.host;
dbCredentials.port = vcapServices[vcapService][0].credentials.port;
dbCredentials.user = vcapServices[vcapService][0].credentials.username;
dbCredentials.password = vcapServices[vcapService][0].credentials.password;
dbCredentials.url = vcapServices[vcapService][0].credentials.url;
cloudant = require('cloudant')(dbCredentials.url);
// check if DB exists if not create
cloudant.db.create(dbCredentials.dbName, function (err, res) {
if (err) { console.log('could not create db ', err); }
});
db = cloudant.use(dbCredentials.dbName);
break;
}
}
if(db==null){
console.warn('Could not find Cloudant credentials in VCAP_SERVICES environment variable - data will be unavailable to the UI');
}
} else{
console.warn('VCAP_SERVICES environment variable not set - data will be unavailable to the UI');
}
}
initDBConnection();
app.get('/', routes.index);
function createResponseData(id, name, phone, attachments) {
var responseData = {
id : id,
name : name,
phone : phone,
attachements : []
};
attachments.forEach (function(item, index) {
var attachmentData = {
content_type : item.type,
key : item.key,
url : '/api/favorites/attach?id=' + id + '&key=' + item.key
};
responseData.attachements.push(attachmentData);
});
return responseData;
}
function createResponseDataProvider(id, provider_type, name, phone, mobile, email, logo, address) {
var responseData = {
id : id,
provider_type: provider_type,
name : name,
phone : phone,
mobile: mobile,
email: email,
logo: logo,
address : address
};
return responseData;
}
//=============get api/rovider/:id================
app.use("/", require('./lib/provider'));
require('./lib/provider');
module.exports.cloudant=cloudant;
module.exports.cloudant1="demo";
http.createServer(app).listen(app.get('port'), '0.0.0.0', function() {
console.log('Express server listening on port ' + app.get('port'));
});
and provider.js file
var router = require('express').Router();
var cloudant= require('../app').cloudant;
var cloudant1= require('../app').cloudant1;
//create del all whitespace of string function
String.prototype.delAllWhiteSpace = function() {
return this.split(' ').join('');
};
var Providers = {
getProvider: function(req, res){
console.log(cloudant);
console.log(cloudant1);
}
};
router.get('/abc/provider/', Providers.getProvider);
module.exports = exports = router;
when calling API http://demo.mybluemix.net/abc/provider, the return results are cloudant undefined

Socket.io socket emit not being called

I have this index.js file on the client:
var socket;
var init = function() {
// Setup Socket:
socket = io.connect();
// Setup Event Handlers:
setEventHandlers();
// Connect to Server:
socket.emit('connect', {
name : "User Name"
});
console.log("Client Init Complete.");
}
var setEventHandlers = function() {
// Set Routes For Connections
socket.on("connection resp", onConnected);
}
var onConnected = function(data) {
console.log(data.resp);
}
And I have this code on the server:
// SETUP:
var express = require('express');
var app = express();
var http = require('http').Server(app);
var request = require('request');
var path = require('path');
var socket = require('socket.io')(http);
var server_port = process.env.OPENSHIFT_NODEJS_PORT || 8080;
var server_ip_address = process.env.OPENSHIFT_NODEJS_IP || '0.0.0.0';
var bodyParser = require('body-parser')
var fs = require('fs');
// SETUP:
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended : false
}));
app.configure(function() {
app.use(express.static(path.join(__dirname, 'public')));
})
var setEventHandlers = function() {
socket.sockets.on("connection", onInit);
};
var onInit = function(client) {
client.on("connect", onConnect);
};
var onConnect = function(data) {
console.log("Called");
}
// Send index page html
app.get('/', function(req, res) {
res.sendfile("public/html/index.html");
});
// Turn on server
http.listen(server_port, server_ip_address, function() {
console.log("App Listening on " + server_ip_address + ", server_port "
+ server_port);
});
setEventHandlers();
The issue is that on the onConnect on the server is never called. Eventhough I call socket.emit("connect") on the client.
After further testing, it seems that the socket id is undefined: this.id returns undefined.
You need to add quotes to the parameters in the socket.emit function like this:
// Connect to Server:
socket.emit('connect', {
'name' : 'User Name'
});
You should initialize your socket variable through io.connect("server address") and has i see in your code you have not passed any parameter to io.connect
.If server is in your local machine then connect to it by io.connect("http://localhost").
For more information see Docs. socket.io-client

Socket.io - Cannot connect to client

I want to implement a simple socket.io connection to a client. For this purpose I use nodeJS with express.
My clients files look like that:
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/0.9.16/socket.io.min.js" />
<!--<script src="http://fb.me/react-0.12.2.min.js"></script>-->
<script src='/javascripts/socket.js'></script>
</head>
<body>
<h1><%= title %></h1>
<p>Welcome to <%= title %> Juhu!</p>
</body>
</html>
socket.js
/**
* socket io connection
*/
var socket = io.connect("http://localhost:3000");
My server site looks like that:
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
//var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
//app.use('/users', users);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
www.js
#!/usr/bin/env node
var debug = require('debug')('Test');
var app = require('../app');
var Pusher = require('pusher-client');
var http = require('http');
app.set('port', process.env.PORT || 3000);
//Create the HTTP server with the express app as an argument
var server = http.createServer(app);
/*var server = app.listen(app.get('port'), function () {
debug('Express server listening on port ' + server.address().port);
});*/
/**
* return pusher data
*/
var API_KEY = 'cb65d0a7a72cd94adf1f';
var pusher = new Pusher(API_KEY, {
encrypted: true
});
var channel = pusher.subscribe("ticker.160");
channel.bind("message", function (data) {
//console.log(data);
});
/**
* Socket.io
*/
var io = require("socket.io").listen(server, {log: true});
var stream = channel.bind("message", function (data) {
//console.log(data);
});
io.sockets.on("connection", function (socket) {
// The user it's added to the array if it doesn't exist
if(users.indexOf(socket.id) === -1) {
users.push(socket.id);
}
// Log
logConnectedUsers();
/*// This is a listener to the signal "something"
stream.on("start stream", function (data) {
console.log("Test: ", data);
socket.emit('info', { data: data });
});*/
// This handles when a user is disconnected
socket.on("disconnect", function(o) {
// find the user in the array
var index = users.indexOf(socket.id);
if(index != -1) {
// Eliminates the user from the array
users.splice(index, 1);
}
logConnectedUsers();
});
});
// A log function for debugging purposes
function logConnectedUsers() {
console.log("============= CONNECTED USERS ==============");
console.log("== :: " + users.length);
console.log("============================================");
}
//server listens
server.listen(app.get('port'), function () {
debug('Express server listening on port ' + server.address().port);
});
I expect when opening my browser I get at least a message that a new client connected in the nodejs app. However, I get nothing.
Any recommendation what I am doing wrong?
UPDATE
I changed the following code, however I still have no connection:
/**
* Socket.io
*/
var io = require("socket.io").listen(server, {log: true});
var stream = channel.bind("message", function (data) {
//console.log(data);
});
io.on("connection", function (socket) {
// The user it's added to the array if it doesn't exist
if(users.indexOf(socket.id) === -1) {
users.push(socket.id);
}
// Log
logConnectedUsers();
socket.emit('someevent', { attr: 'value' } )
/*// This is a listener to the signal "something"
stream.on("start stream", function (data) {
console.log("Test: ", data);
socket.emit('info', { data: data });
});*/
// This handles when a user is disconnected
socket.on("disconnect", function(o) {
// find the user in the array
var index = users.indexOf(socket.id);
if(index != -1) {
// Eliminates the user from the array
users.splice(index, 1);
}
logConnectedUsers();
});
});
Thats all of my console output, when callinglocalhost:3000`
Wed, 31 Dec 2014 11:24:00 GMT Test Express server listening on port 3000
GET / 304 19.798 ms - -
GET /stylesheets/style.css 304 15.385 ms - -
UPDATE
My index.js route file:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res) {
res.render('index', { title: 'Express' });
});
module.exports = router;
Update
I am now loadign my socket.js script from the client on the end of my page and get the following error message:
GET http://localhost:3000/socket.io/1/?t=1420027015782 400
(Bad Request)socket.io.min.js:2 d.handshakesocket.io.min.js:2 d.connectsocket.io.min.js:2 dsocket.io.min.js:2 c.connectsocket.js:4 (anonymous function)
What you have until now, (strictly speaking) is client connecting to server. (html+socket.js calling io.connect() ).
Maybe you're asking about sending the data from server to the client?
Inside pherris's function, you can send the data to the client with
io.on('connection', function (socket) {
console.log('a user connected')
socket.emit('someevent', { attr: 'value' } )
})
and catch it on the client side again with
var socket = io.connect("http://localhost:3000");
socket.on('someevent', function (data) { console.log(data) })
And there send another event to the server.
The communication can be done in both ways. Depends on your needs.

Setting up a MongoDB database connection with node.js

How would I set up a MongoDB database connection with node.js?
Here is my app.js file:
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);
server.listen(3000);
app.get('/', function(req, res) {
res.sendfile(__dirname + '/index.htm');
});
app.use(express.static(__dirname + '/assets'));
io.sockets.on('connection', function(socket) {
socket.on('send message', function(data) {
io.sockets.emit('new message', data);
});
});
I have already set-up MongoDB and have it running as a service on Windows.
As of 1.2, the recommended way to perform a connection is in documentation:
http://mongodb.github.io/node-mongodb-native/driver-articles/mongoclient.html
excerpt:
var MongoClient = require('mongodb').MongoClient
, Server = require('mongodb').Server;
var mongoClient = new MongoClient(new Server('localhost', 27017));
mongoClient.open(function(err, mongoClient) {
var db1 = mongoClient.db("mydb");
mongoClient.close();
});
You may find that a connection singleton is useful for the current state of the official node.js driver. Below is some sample code that I use:
connection.js module:
var MongoClient = require('mongodb').MongoClient;
var db_singleton = null;
var getConnection= function getConnection(callback)
{
if (db_singleton)
{
callback(null,db_singleton);
}
else
{
//placeholder: modify this-should come from a configuration source
var connURL = "mongodb://localhost:27017/test";
MongoClient.connect(connURL,function(err,db){
if(err)
log("Error creating new connection "+err);
else
{
db_singleton=db;
log("created new connection");
}
callback(err,db_singleton);
return;
});
}
}
module.exports = getConnection;
Referencing module:
var getConnection = require('yourpath/connection.js')
function yourfunction()
{
getConnection(function(err,db)
{
//your callback code
}
.
.
.
}

Categories

Resources