MrB*_*les 21 javascript node.js express socket.io
我知道我可以用
function(req, res) {
req.session
}
Run Code Online (Sandbox Code Playgroud)
使用快递.但是我需要访问响应函数之外的会话.我该怎么做呢?
我正在使用socket.io来传递添加帖子和评论的信息.因此,当我在服务器端收到socket.io消息时,我需要使用会话验证发布信息的人.但是,由于这是通过socket.io完成的,因此没有req/res.
小智 10
我想我有一个不同的答案.
码:
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
}));
Run Code Online (Sandbox Code Playgroud)
那么你应该在req中定义一个会话密钥,就像:
码:
req.session.userEmail;
Run Code Online (Sandbox Code Playgroud)
最后,你可以这样得到它:
码:
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);
});
}
Run Code Online (Sandbox Code Playgroud)
我昨天做过测试,效果很好.
使用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;
};
Run Code Online (Sandbox Code Playgroud)
然后在您的授权方法上,我使用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 );
}
});
}
Run Code Online (Sandbox Code Playgroud)
然后在模型中保存记录之前,您可以执行以下操作:
model._author = shished.getHandshakeValue( socket, 'userId' );