Express - socket.io - 阅读会话

发布于 2024-12-27 12:05:58 字数 2416 浏览 1 评论 0原文

我使用 Express 和 socket.io。

当您使用特快专递创建会话时。单击按钮并使用 Ajax 和 POST 方法(登录)保存会话。

 app.post('/login', function(req, res){
         req.session.loginid = req.body.lgnid;
    });

在socket.io中它无法读取。

我的源代码:

var express = require('express');
var app = express.createServer();
var io = require('socket.io').listen(app); 
var MemoryStore = express.session.MemoryStore;
var sessionStore = new MemoryStore();
var parseCookie = require('connect').utils.parseCookie;
var Session = require('connect').middleware.session.Session;
var stylus = require('stylus');
  app.use(express.bodyParser());
  app.use(express.cookieParser());
  app.use(express.session({store: sessionStore
        , secret: 'secret'
        , key: 'express.sid'}));

  app.use(stylus.middleware({ src: __dirname + '/public', compile: compile }))
  app.use(express.static(__dirname + '/public'));
  app.set('views', __dirname);

 // disable layout
  app.set("view options", {layout: false});

  // make a custom html template
  app.register('.html', {
    compile: function(str, options){
      return function(locals){
        return str;
      };
    }
  });

  function compile (str, path) {
    return stylus(str)
      .set('filename', path)
      .use(nib());
  };

var Session = require('connect').middleware.session.Session;
sio.set('authorization', function (data, accept) {
    if (data.headers.cookie) {
        data.cookie = parseCookie(data.headers.cookie);
        data.sessionID = data.cookie['express.sid'];
        // save the session store to the data object 
        // (as required by the Session constructor)
        data.sessionStore = sessionStore;
        sessionStore.get(data.sessionID, function (err, session) {
            if (err || !session) {
                accept('Error', false);
            } else {
                // create a session object, passing data as request and our
                // just acquired session data
                data.session = new Session(data, session);
                accept(null, true);
            }
        });
    } else {
       return accept('No cookie transmitted.', false);
    }
});

如何从sessionStore加载和保存数据?

io.sockets.on('connection', function (socket) {
 
    var hs = socket.handshake;
    console.log('Session : ' + hs.session.loginid + '); //Session : undefined

});

I use Express and socket.io.

When you create a session with the express - post. Click the button and using Ajax and the POST method (login), I save a session.

 app.post('/login', function(req, res){
         req.session.loginid = req.body.lgnid;
    });

In socket.io it can not read.

My source code:

var express = require('express');
var app = express.createServer();
var io = require('socket.io').listen(app); 
var MemoryStore = express.session.MemoryStore;
var sessionStore = new MemoryStore();
var parseCookie = require('connect').utils.parseCookie;
var Session = require('connect').middleware.session.Session;
var stylus = require('stylus');
  app.use(express.bodyParser());
  app.use(express.cookieParser());
  app.use(express.session({store: sessionStore
        , secret: 'secret'
        , key: 'express.sid'}));

  app.use(stylus.middleware({ src: __dirname + '/public', compile: compile }))
  app.use(express.static(__dirname + '/public'));
  app.set('views', __dirname);

 // disable layout
  app.set("view options", {layout: false});

  // make a custom html template
  app.register('.html', {
    compile: function(str, options){
      return function(locals){
        return str;
      };
    }
  });

  function compile (str, path) {
    return stylus(str)
      .set('filename', path)
      .use(nib());
  };

var Session = require('connect').middleware.session.Session;
sio.set('authorization', function (data, accept) {
    if (data.headers.cookie) {
        data.cookie = parseCookie(data.headers.cookie);
        data.sessionID = data.cookie['express.sid'];
        // save the session store to the data object 
        // (as required by the Session constructor)
        data.sessionStore = sessionStore;
        sessionStore.get(data.sessionID, function (err, session) {
            if (err || !session) {
                accept('Error', false);
            } else {
                // create a session object, passing data as request and our
                // just acquired session data
                data.session = new Session(data, session);
                accept(null, true);
            }
        });
    } else {
       return accept('No cookie transmitted.', false);
    }
});

How to load and save data from sessionStore?

io.sockets.on('connection', function (socket) {
 
    var hs = socket.handshake;
    console.log('Session : ' + hs.session.loginid + '); //Session : undefined

});

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

失去的东西太少 2025-01-03 12:05:58

实际上(至少根据我的经验)实现此目的的推荐方法是放弃 sessionStore.get 函数并转而使用 sessionStore.load - 区别在于使用 load回调会被赋予一个会话实例,而不必自己创建一个。区别只是简单地获取您的代码片段:

sessionStore.get(data.sessionID, function (err, session) {
    if (err || !session) {
        accept('Error', false);
    } else {
        // create a session object, passing data as request and our
        // just acquired session data
        data.session = new Session(data, session);
        accept(null, true);
    }
});

并将其更改为:

sessionStore.load(data.sessionID, function(err, session) {
  if (err || !session) {
    accept("Error", false);
  } else {
    data.session = session;
    accept(null, true);
  }
});

从那里,您应该能够在尝试时访问会话,例如 socket.handshake.session,但是在处理会话时如果您在套接字事件中进行更改,则必须自己手动保存会话。如果添加/删除内容,则必须:session.save([callback])

我意识到这并不是一个很好的答案,因为我告诉你大致做你已经做的事情,但这现在对我来说适用于 Express 2.5.8 和 Socket.IO 0.9.6。

A recommended way to achieve this actually (at least in my experience) is to forgo the sessionStore.get function and go for sessionStore.load instead - the difference is that with load the callback is given a session instance instead of having to create one yourself. The difference is simply taking your snippet:

sessionStore.get(data.sessionID, function (err, session) {
    if (err || !session) {
        accept('Error', false);
    } else {
        // create a session object, passing data as request and our
        // just acquired session data
        data.session = new Session(data, session);
        accept(null, true);
    }
});

And changing it to:

sessionStore.load(data.sessionID, function(err, session) {
  if (err || !session) {
    accept("Error", false);
  } else {
    data.session = session;
    accept(null, true);
  }
});

And from there, you should be able to access the session as you attempt, such as socket.handshake.session, however when dealing with the session if you make changes in a socket event you have to manually save the session yourself. If you add/remove things you must: session.save([callback]).

I realize this isn't much of an answer since I'm telling you to do roughly what you already are but this is working for me right now with Express 2.5.8 and Socket.IO 0.9.6.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文