如何在需求以外的快速访问会话?

我知道我可以使用

function(req, res) { req.session } 

使用快递。 但是我需要访问响应函数之外的会话。 我将如何去做呢?

我使用socket.io传递信息添加post和评论。 因此,当我在服务器端收到socket.io消息时,需要使用会话来validation发布信息的人员。 但是,因为这是通过socket.io来完成,所以没有req / res。

使用socket.io,我已经用一个简单的方法完成了。 我假设你有一个对象为你的应用程序让我们说,MrBojangle,我的它叫做Shished:

 /** * Shished singleton. * * @api public */ function Shished() { }; Shished.prototype.getHandshakeValue = function( socket, key, handshake ) { if( !handshake ) { handshake = socket.manager.handshaken[ socket.id ]; } return handshake.shished[ key ]; }; Shished.prototype.setHandshakeValue = function( socket, key, value, handshake ) { if( !handshake ) { handshake = socket.manager.handshaken[ socket.id ]; } if( !handshake.shished ) { handshake.shished = {}; } handshake.shished[ key ] = value; }; 

然后在您的授权方法中,我使用MongoDB进行会话存储:

 io.set('authorization', function(handshake, callback) { self.setHandshakeValue( null, 'userId', null, handshake ); if (handshake.headers.cookie) { var cookie = connect.utils.parseCookie(handshake.headers.cookie); self.mongoStore() .getStore() .get(cookie['connect.sid'], function(err, session) { if(!err && session && session.auth && session.auth.loggedIn ) { self.setHandshakeValue( null, 'userId', session.auth.userId, handshake ); } }); } 

然后,在模型中保存logging之前,您可以执行以下操作:

model._author = shished.getHandshakeValue( socket, 'userId' );

我想我有一个不同的答案。

码:

 var MongoStore = require('connect-mongo')(session); var mongoStore = new MongoStore({ db:settings.db, //these options values may different port:settings.port, host:settings.host }) app.use(session({ store : mongoStore //here may be more options,but store must be mongoStore above defined })); 

那么你应该在req上定义一个会话密钥,就像:

码:

 req.session.userEmail; 

最后,你可以这样做:

码:

 var cookie = require("cookie"); //it may be defined at the top of the file io.on("connection",function(connection){ var tS = cookie.parse(connection.handshake.headers.cookie)['connect.sid']; var sessionID = tS.split(".")[0].split(":")[1]; mongoStore.get(sessionID,function(err,session){ console.log(session.userEmail); }); } 

我昨天testing过了,效果很好。

假设你的socket.io代码看起来有点像这样:

 io.on('connection', function(client) { console.log(client.request) }); 

请求是client.request ,如上例所示。

编辑:作为一个单独的事情,也许这将有助于: https : //github.com/aviddiviner/Socket.IO-sessions

我相信检查socket.handshake应该让你的会议:

 io.sockets.on('connection', function(socket) { console.log(socket.handshake.sessionID); }); 

当客户端与您的socket.io服务器build立套接字连接时,客户端发送一个WebSocket握手请求。 我上面做的是从握手中获取会话ID。