Express Socket.io example server not working - node.js

I'm trying to learn socket.io and their example for Express isnt working. Heres my code:
app.js:
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, server = require('http').createServer(app)
, path = require('path')
, io = require('socket.io').listen(app);
var app = express();
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(require('less-middleware')({ src: __dirname + '/public' }));
app.use(express.static(path.join(__dirname, 'public')));
server.listen(3000);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.jade');
});
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
and my index.jade file:
extends layout
block content
script(src="/node_modules/socket.io/lib/socket.io.js")
script(
var socket = io.connect('http://localhost:3000');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
)
When I go to my localhost the browser just keeps waiting on a response. It eventually times out.
Most of the other questions related to this question had some odd implementation of the example code. I'm literally just trying to implement it as they show.

The problem is you are creating app after you are creating io. So this line
, io = require('socket.io').listen(app);
is effectively the same as
, io = require('socket.io').listen(undefined);
remove this line
var app = express();
And somewhere between the first line and io = require('socket.io') add , app = express()

Related

Socket.IO with Express.JS routing

Creating my small chat wasn't too hard, but now I am trying to create real-time comments system. My current configuration uses latest Node, Express and Socket.IO and I have no idea how to create separate comment page. How to connect Express' routing and SocketIO when routes are defined before I can open socket connection?
var express = require('express');
var app = express();
var swig = require('swig');
app.engine('html', swig.renderFile);
app.set('view engine', 'html');
app.set('views', __dirname + '/views');
app.set('view cache', false);
app.use(express.static(__dirname + '/public'));
swig.setDefaults({ cache: false });
app.get('/', function (req, res) {
res.render('chat');
});
var server = app.listen(80);
var io = require('socket.io').listen(server);
io.on('connection', function (socket) {
socket.emit('open', messages);
socket.on('message', function (data) {
socket.broadcast.emit('message', data);
});
});

Socket.io 'on' is returning undefined

Ok, so I'm trying to learn socket.io and I get this error:
io.socket.on('connection', function (socket)
TypeError: Cannot call method 'on' of undefined
heres my code:
var express = require('express')
, app = express.createServer()
, routes = require('./routes')
, user = require('./routes/user')
, path = require('path')
, io = require('socket.io').listen(app);
// all environments
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
app.listen(3000);
app.get('/', routes.index);
app.get('/users', user.list);
io.socket.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
I know its going to be something rather obvious.
Should be io.sockets.on ("sockets" instead of "socket"):
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
I think that this code is no longer working.
Here is something I made to deal with socket.io and a http server.
var app = require('http'),
io = require('socket.io');
var handler = function(req, res) { /* your handler function*/ };
var server = app.createServer(handler).listen( 8000 );
var ios = io.listen(server);
ios.sockets.on('connection', function(socket){
socket.emit('message', {'message': 'hello world'});
});

express/node app stops listening after a few requests

what I'm trying to achieve is to accept requests for a value, add that value to an array, run a function on it that'll query it and then remove it from the array with the shift function. What I have so far is a simplified framework of that, but it's now giving me this error.
RangeError: Maximum call stack size exceeded
if there's anything I can do to improve my code as well please let me know.
app.js
var express = require('express')
, http = require('http')
, path = require('path')
, fs = require('fs')
, eventEmitter = require('events').EventEmitter;
var app = express();
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
var ee = new eventEmitter;
var queries = new Array();
ee.on('next', next_search);
function next_search() {
console.log(queries);
search();
}
function search() {
// do something
queries.shift();
console.log(queries);
ee.emit('next')
}
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
app.post('/search', function(req, res) {
letter = req.param('letter');
console.log(letter);
queries.push(letter);
next_search();
});
http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
jQuery code
$(document).ready(function() {
$('#letter').on("keyup", function() {
letter = $('#letter').val();
$.post("/search", { letter: letter}, function(data) {
$('#status').html(data);
});
});
});
This is an infinite function call, when you post. next_search -> search ->ee next event-> next_search -> ...
ee.on('next', next_search);
function next_search() {
console.log(queries);
search();
}
function search() {
// do something
queries.shift();
console.log(queries);
ee.emit('next') // execute first line
// only do this when queries is non-empty
}
You should check if queries is not empty, only then do next_search.

backbone.js sending "OPTIONS" as a restful request

Backbone talking to node/express running locally os x 10.6.8. Trying to populate a clientside backbone model with fetch. Thinking I have fetch wrong. Most of app_stuff.js is cut-and-paste. Curious why node/express sees the request as OPTIONS instead of GET (or POST?) and if I have the terminology right. I think I can make it work like this but would rather pay the dues for some best practices while still an absolute newb.
backbone
(function($) {
var Stuff = Backbone.Model.extend({
});
var Collec = Backbone.Collection.extend({
model: Stuff,
url: 'http://localhost:3000/stuff'
});
var nstuff = new Collec;
nstuff.fetch(
{ data: $.param({ name: "helloworld"}) }
);
})(jQuery);
app_stuff.js
var express = require('express')
, routes = require('./routes')
, stuff = require('./routes/stuff')
, user = require('./routes/user')
, http = require('http')
, path = require('path');
var app = express();
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/users', user.list);
app.get('/stuff', stuff.index);
app.options('/stuff', function() { console.log("stuffed"); });
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
terminal output
$ node timeline/app_stuff.js
Express server listening on port 3000
stuffed

Express: unable to access POST data and set cookie at the same time

I'm writing an application that takes in a post request and sets a cookie pulled from the POST info. I'm stuck in a catch 22. In the first code sample I can set the cookie but can't access the data, in the second I can access the data but can't set the cookie. I'm sure I'm missing some basic concept of how the middle ware works but I can't for the life of me find the info I need.
The code below creates the cookie as expected but my post variable become undefined
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, handshake = require('./routes/handshake')
, http = require('http')
, path = require('path');
var app = express();
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(function (req, res, next) {
var cookie = req.cookies.cokkieName;
console.log("cookie_name" , cookie);
if (cookie === undefined)
{
//cookie is set but I can't use req.post.xxxx. It"s always undefined
res.cookie("price", 111, { maxAge: 10000 });
console.log('cookie has been created successfully');
}
else
{
console.log('cookie exists', cookie);
}
next();
});
app.use(app.router);
app.use(require('stylus').middleware(__dirname + '/public'));
app.use(express.static(path.join(__dirname, 'public')));
app.post('/handshake', handshake.token);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
The following code executes the setCookie callback (because the console output shows up), and on the console the variables are properly defined, but the cookie is not set.
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, handshake = require('./routes/handshake')
, http = require('http')
, path = require('path');
var app = express();
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.methodOverride());
var setCookie = function (req, res, next) {
var cookie = req.cookies.cokkieName;
console.log("cookie_name" , cookie);
if (cookie === undefined)
{
res.cookie("price", 111, { maxAge: 10000 });
//in the console the post.body.xxxx data appears correctly but no cookie!!!
console.log('cookie has been created successfully',post.body.xxx);
}
else
{
console.log('cookie exists', cookie);
}
next();
};
app.use(app.router);
app.use(require('stylus').middleware(__dirname + '/public'));
app.use(express.static(path.join(__dirname, 'public')));
app.post('/handshake', setCookie ,handshake.token);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
Trying to make the code more readable introduced too many typos that weren't relevant to my code. I took the suggestion and changed the code in the following way but it still doesn't write a cookie to the client.
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, handshake = require('./routes/handshake')
, http = require('http')
, crypt = require('crypto')
, io = require('socket.io')
, db = require('levelup')('./mydb')
, path = require('path');
var app = express();
app.use(express.cookieParser());
app.use(express.bodyParser());
var cookieMiddleware = function (req, res, next) {
var cookie = req.cookies.user;
console.log("cookie_name" , cookie);
if (cookie === undefined)
{
// no: set a new cookie
var random = Math.random().toString();
random=random.substring(2,random.length);
sessionToken = Date.now() + random;
salt = sessionToken + req.body.address;
sha2 = crypt.createHash('sha256');
sha2.update(sessionToken);
var price = req.body.price;
var encryptedSession = sha2.digest('hex');
console.log('post body',price );
res.cookie('user','price' , { maxAge: 100000 });
console.log('existing cookies', req.cookies);
}
else
{
console.log('cookie exists', req.cookies);
}
next();
};
//development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.logger('dev'));
app.use(express.session({secret: "TheSuperSecretStringForHashing"}));
app.use(express.methodOverride());
app.use(app.router);
//app.use(express.favicon());
app.use(require('stylus').middleware(__dirname + '/public'));
app.use(express.static(path.join(__dirname, 'public')));
app.post('/handshake', cookieMiddleware , handshake.token);
app.get('/', routes.index);
app.get('/users', user.list);
var server = http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
io = io.listen(server);
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
The handshake.js handler
exports.token = function(req, res){
req.body.title = 'Payment Portal';
res.render('payment_init', req.body);
};
You are checking for a cookie named cokkieName, but the cookie you are setting has the name price.
Try changing this to:
var cookie = req.cookies.price;
cookie should now contain your cookie value.

Resources