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为何未定义,安全显示为未定义。

最佳答案

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
});

10-06 16:16