如何在请求之外快速访问会话? [英] How to access session in express, outside of the req?
问题描述
我知道我可以使用
function(req, res) {
req.session
}
使用快递.但是我需要在响应函数之外访问会话.我该怎么做?
using express. However I need to access the session outside of the response function. How would I go about doing that?
我正在使用 socket.io 传递信息以添加帖子和评论.所以当我在服务器端收到socket.io消息时,我需要使用会话来验证发布信息的人.但是,由于这是通过 socket.io 完成的,因此没有 req/res.
I'm using socket.io to pass information for adding posts and comments. So when I receive the socket.io message on the server-side, I need to verify the person posting the information by using the session. However since this is being done via socket.io there is no req/res.
推荐答案
使用 socket.io,我以一种简单的方式完成了这项工作.我假设你的应用程序有一个对象,比如说 MrBojangle,我的它叫做 Shished:
Using socket.io, I've done this in a simple way. I assume you have an object for your application let's say MrBojangle, for mine it's called 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 进行会话存储:
Then on your authorization method, I'm using MongoDB for session storage:
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 );
}
});
}
然后在模型中保存记录之前,您可以:
Then before saving a record in the model, you can do:
model._author = shished.getHandshakeValue(socket, 'userId');
这篇关于如何在请求之外快速访问会话?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!