I have this code in my server.js.
var app = require('express')(),
session = require('express-session'),
cookie = require('cookie'),
cookieParser = require('cookie-parser'),
manager = require('./sockets/manager');
var sessionStore = new session.MemoryStore();
app.use(cookieParser('secret'));
app.use(session({
name: 'sid',
store: sessionStore,
secret: 'secret',
saveUninitialized: true,
resave: true,
cookie: {
path: '/',
httpOnly: true,
secure: false,
maxAge: null
}
}));
var server = require('http').Server(app).listen(8888),
io = require('socket.io')(server);
io.use(function(socket, next) {
var data= socket.request;
if (data.headers.cookie) {
data.cookie = cookie.parse(cookieParser.signedCookie(data.headers.cookie, 'secret'));
console.log('data.cookies ( %s )', JSON.stringify(data.cookie));
// print 'io=id_place', cookies doesn't have sid, why?
if (data.cookie.sid) {
data.sid = request.cookie.sid;
sessionStore.get(request.cookie.sid, function(err, session) {
request.session = session;
});
}
}
next();
});
manager.use(io);
Console log shows me this cookie request.cookies ( {"io":"lHKSseNH5UrnJisSAAAA"} ). I've just seen many examples with expressjs 3 and socket 0.9, but I have:
"socket.io": "^1.0.6", "express": "~4.5.1", "express-session": "~1.6.4"
and it doesn't work.
Have I any mistakes?
The below link has a very simple solution to share session between Express and Socket.IO.
Simple Answer
The middleware API of Express 4.x is so close to Socket.IO 1.x that we can use the same session middleware for both.
The example over there uses MongoDB session store. I tried with the express-session's default session store and it worked.
io.js
app.js
bin/www
Hope this might help any future users.
P.S: I used express-generator so this kind of module split.
I've created solution for you: enter link description here. As you can see socket object has handshake property which include request headers with cookie.
Try this module express-socket.io-session.
It allows you to shared cookie-based session data between express and socket.io (and viceversa).
You can use whatever storage you want for session data because you create the express-session object in a regular way and then share it with socket.io.
It works for express >4.0 and socket.io >1.0