Node.js - Express.io:在不同的浏览器中保存不同的会话

时间:2013-05-19 00:15:30

标签: node.js express session-variables

如何以及是否正确保存会话在node.js'express.io(所有最新版本)中来自不同浏览器。 我怎么能解决这个不端行为?

代码:

app.get('/home', function(req, res) {
    req.session.variable = 'value';
    req.session.save(function() {
        console.log(req.session);
    });
    res.send('<script src="/socket.io/socket.io.js"></script>\
              <script>var socket = io.connect();</script>\
              Home content');
});

app.io.route('disconnect', function(req) {
    console.log('-------------------------------');
    console.log(req.session);
    req.session.variable = '';
    req.session.save(function() {
        console.log(req.session);
        console.log('-------------------------------');
    });
});

情况: 我在/home页面上,然后重新加载页面。 重新加载后,除Chrome之外的每个(?)浏览器中控制台的输出:

{ cookie:
   { path: '/',
     _expires: Mon May 19 2014 01:40:59 GMT+0200,
     originalMaxAge: 31536000000,
     httpOnly: true },
  variable: 'value' }

// RELOAD:

-------------------------------
{ cookie:
   { originalMaxAge: 31536000000,
     expires: '2014-05-18T23:40:59.399Z',
     httpOnly: true,
     path: '/' },
  variable: 'value',
  touch: [Function],
  resetMaxAge: [Function],
  save: [Function],
  reload: [Function],
  destroy: [Function],
  regenerate: [Function] }
{ cookie:
   { originalMaxAge: 31536000000,
     expires: '2014-05-18T23:40:59.399Z',
     httpOnly: true,
     path: '/' },
  variable: '',
  touch: [Function],
  resetMaxAge: [Function],
  save: [Function],
  reload: [Function],
  destroy: [Function],
  regenerate: [Function] }
-------------------------------
{ cookie:
   { path: '/',
     _expires: Mon May 19 2014 01:41:03 GMT+0200,
     originalMaxAge: 31536000000,
     httpOnly: true },
  variable: 'value' }

在Chrome中:

{ cookie:
   { path: '/',
     _expires: Mon May 19 2014 00:43:37 GMT+0200,
     originalMaxAge: 31536000000,
     httpOnly: true },
  variable: 'value' }

// RELOAD

{ cookie:
   { path: '/',
     _expires: Mon May 19 2014 00:43:37 GMT+0200,
     originalMaxAge: 31536000000,
     httpOnly: true },
  variable: 'value' }
-------------------------------
{ cookie:
   { originalMaxAge: 31536000000,
     expires: '2014-05-18T23:36:58.926Z',
     httpOnly: true,
     path: '/' },
  variable: 'value',
  touch: [Function],
  resetMaxAge: [Function],
  save: [Function],
  reload: [Function],
  destroy: [Function],
  regenerate: [Function] }
{ cookie:
   { originalMaxAge: 31536000000,
     expires: '2014-05-18T23:36:58.926Z',
     httpOnly: true,
     path: '/' },
  variable: '',
  touch: [Function],
  resetMaxAge: [Function],
  save: [Function],
  reload: [Function],
  destroy: [Function],
  regenerate: [Function] }
-------------------------------

这可能是Chrome的错误而不是express.io? Chrome中的日志顺序与其他浏览器不同,这也很奇怪。

我需要的是,如果用户导航离开某个页面(设置该变量),则应该删除/清空会话变量。

1 个答案:

答案 0 :(得分:0)

我想我很久以前通过将此设置设置为在客户端同步卸载断开连接来解决问题:

var socket = io.connect('your-socket-url.com', {
    'sync disconnect on unload': true
});