js,express,redis(用于内存存储)和socket.io。我正在尝试设置经过身份验证的套接字调用以匹配每个用户的套接字。我有这个代码在大多数情况下执行它除了某些原因sessionID显示为未定义并获得错误加载会话(握手错误)。
以下是代码:
var io = require('socket.io');
var notificationsN = io.listen(server);
var RedisStore = require('connect-redis')(express);
var redis = require("redis").createClient();
var cookie = require('cookie');
var session_store = new RedisStore({client: redis});
app.use(express.session({
secret: "secret",
store: new RedisStore({ host: 'localhost', port: 3000, client: redis })
}));
notificationsN.configure(function() {
notificationsN.set('authorization', function(data, accept) {
console.log('data below');
console.log(data);
console.log('data sid below');
console.log(data.sessionID);
if(!data.headers.cookie ) return accept( new Error('No user cookie found'), true );
data.cookie = cookie.parse( data.headers.cookie, { secure: true } );
data.cookie = connect.utils.parseSignedCookies( data.cookie, config.session.secret );
data.cookie = connect.utils.parseJSONCookies( data.cookie );
data.sessionID = data.cookie[config.session.key];
session_store.load( data.sessionID, function( err, session ){
if( err || !session ) return accept( new Error('Error loading session'), false );
data.session = session;
return accept( null, true );
});
console.log(data);
})
})
notificationsN.on('connection', function(socket) {
socket.on('message', function(msg) {
console.log(msg);
});
socket.on('disconnect', function() {
console.log('disconnecting from redis');
});
});
以下是我从console.log(data)
获取的内容:
{ headers:
{ host: 'localhost:3000',
connection: 'keep-alive',
'cache-control': 'max-age=0',
'user-agent': 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTM
L, like Gecko) Chrome/29.0.1547.57 Safari/537.36',
accept: '*/*',
referer: 'http://localhost:3000/userProfile',
'accept-encoding': 'gzip,deflate,sdch',
'accept-language': 'en-US,en;q=0.8',
cookie: 'connect.sid=crazyvalue; __atuvc=crazyvalue; userid=crazyvalue' },
address: { address: 'ip', port: port},
time: 'Fri Aug 30 2013 15:50:31 GMT-0400 (Eastern Daylight Time)',
query: { t: '1377892231624' },
url: '/socket.io/1/?t=1377892231624',
xdomain: false,
secure: undefined,
issued: 1377892231630,
cookie: {},
sessionID: undefined }
所以不确定为什么sessionID未定义且安全显示为未定义。
答案 0 :(得分:0)
session_store.load
是异步的。您需要将console.log移动到此函数的回调中。
session_store.load( data.sessionID, function( err, session ){
if( err || !session ) return accept( new Error('Error loading session'), false );
data.session = session;
console.log(data);//Move it here.
return accept( null, true ); //This return statement is doing nothing useful
});