0

不同浏览器的 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 中的日志顺序与任何其他浏览器都不同,这也很奇怪。

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

4

1 回答 1

0

我想我很久以前通过设置此设置来同步客户端卸载时的断开连接来解决问题,如下所示:

var socket = io.connect('your-socket-url.com', {
    'sync disconnect on unload': true
});
于 2013-10-04T00:05:19.800 回答