简体   繁体   English

如何使用Socket.io和Express处理会话?

[英]How to handle sessions with Socket.io and Express?

I have an application up and running. 我有一个应用程序启动并运行。 Users requested that after they log in they would stay logged when they come back later. 用户在登录后要求他们在以后回来时会保持记录状态。

I know that I need somehow store session data on client side, cookies for example. 我知道我需要在客户端以某种方式存储会话数据,例如cookie。 I tried this https://stackoverflow.com/a/25618636/2440515 but it doesn't work. 我试过这个https://stackoverflow.com/a/25618636/2440515但它不起作用。 Neither this https://www.npmjs.com/package/socket.io-handshake 这不是https://www.npmjs.com/package/socket.io-handshake

I have both Express and Socket.io in the latests versions. 我有最新版本的Express和Socket.io。

My application authenticates using Socket.io, so I will need a way to update cookies from Socket.io callback. 我的应用程序使用Socket.io进行身份验证,因此我需要一种方法来更新Socket.io回调中的cookie。 I spent last 4h searching and trying different solutions. 我花了4小时搜索并尝试不同的解决方案。 Can someone give me a hint? 有人能给我一个暗示吗?

Thank you! 谢谢!

You can use coockie module for resolve the cookies passed: 您可以使用coockie模块来解析传递的cookie:

$ npm install cookie

On code: 代码:

//...
var cookie = require('cookie');
//...
io.use(function (socket, next) {
   var cookies = cookie.parse(socket.request.headers.cookie);

   var my_secret = cookies.my_secret || null;

   if (!my_secret) {
       return next(new Error('No cookie set'));
   }

   validateMySecretAsync(my_secret, next);

});
// ....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM