在nodejs中设置会话数据表示socket.io

时间:2013-10-05 17:56:45

标签: node.js session express socket.io

我正在尝试从互联网上收集的以下代码

var io = require('socket.io'),
express = require('express'),
app = express(),
server = require('http').createServer(app),
connect = require('express/node_modules/connect');

var RedisStore = require("connect-redis")(express);
var sessionStore = new RedisStore()

var sessionSecret = 'sexret';
var sessionKey = 'sexpress.sid';
var sioCookieParser = express.cookieParser(sessionSecret);

app.configure(function() {
   app.use(connect.cookieParser());
   app.use(connect.session({ store: sessionStore, secret: sessionSecret, key: sessionKey }));
   app.use(express.static(__dirname + '/public'));
});

var sio = io.listen(server);

sio.set('authorization', function(data, accept) {
   sioCookieParser(data, {}, function(err) {
      if (err) {
        accept(err, false);
      } else {
        sessionStore.get(data.signedCookies[sessionKey], function(err, session) {
            if (err || !session) {
                accept('Session error', false);
            } else {
                // I'm trying to set data in to the session

                if (session.yyy) {
                    session.yyy += 1;
                } else {
                    session.yyy = 0;
                }

                console.log("%j", session);

                // But it never set

                data.session = session;
                data.sessionId = data.signedCookies[sessionKey];
                accept(null, true);
            }
        });
      }
  });
});

server.listen(1337);

我也尝试了这个,但它也没有用,

sessionStore.get(data.signedCookies[sessionKey], function(err, session) {
  if (err || !session) {
    accept('Session error', false);
  } else {

    if (session.yyy) {
        session.yyy += 1;
    } else {
        session.yyy = 0;
    }

    console.log("%j", session);

    sessionStore.set(data.signedCookies[sessionKey], session, function(err, session) {

       data.session = session;
       data.sessionId = data.signedCookies[sessionKey];
       accept(null, true);

    });
  }

});

我应该如何将数据设置到会话中?

1 个答案:

答案 0 :(得分:0)

看起来 sessionId 应该是 sessionID ,正如Morgan在这个答案中提到的那样:

https://stackoverflow.com/a/9676844/80122