I use express and socket.io.
When you create a session with the express - post. Click the button and using Ajax and the POST method (login), I save a session.
app.post('/login', function(req, res){
req.session.loginid = req.body.lgnid;
});
In socket.io it can not read.
Thanks for the advice.
My source code.:
var express = require('express');
var app = express.createServer();
var io = require('socket.io').listen(app);
var MemoryStore = express.session.MemoryStore;
var sessionStore = new MemoryStore();
var parseCookie = require('connect').utils.parseCookie;
var Session = require('connect').middleware.session.Session;
var stylus = require('stylus');
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({store: sessionStore
, secret: 'secret'
, key: 'express.sid'}));
app.use(stylus.middleware({ src: __dirname + '/public', compile: compile }))
app.use(express.static(__dirname + '/public'));
app.set('views', __dirname);
// disable layout
app.set("view options", {layout: false});
// make a custom html template
app.register('.html', {
compile: function(str, options){
return function(locals){
return str;
};
}
});
function compile (str, path) {
return stylus(str)
.set('filename', path)
.use(nib());
};
var Session = require('connect').middleware.session.Session;
sio.set('authorization', function (data, accept) {
if (data.headers.cookie) {
data.cookie = parseCookie(data.headers.cookie);
data.sessionID = data.cookie['express.sid'];
// save the session store to the data object
// (as required by the Session constructor)
data.sessionStore = sessionStore;
sessionStore.get(data.sessionID, function (err, session) {
if (err || !session) {
accept('Error', false);
} else {
// create a session object, passing data as request and our
// just acquired session data
data.session = new Session(data, session);
accept(null, true);
}
});
} else {
return accept('No cookie transmitted.', false);
}
});
How to load and save data from sessionStore?
io.sockets.on('connection', function (socket) {
var hs = socket.handshake;
console.log('Session : ' + hs.session.loginid + '); //Session : undefined
});