如何与Socket.io 1.0和Express 4.x共享会话?我使用Redis商店,但我认为这没有关系。我知道我必须使用中间件来查看cookie和获取会话,但是不知道如何。我搜索了但找不到任何工作
var RedisStore = connectRedis(expressSession); var session = expressSession({ store: new RedisStore({ client: redisClient }), secret: mysecret, saveUninitialized: true, resave: true }); app.use(session); io.use(function(socket, next) { var handshake = socket.handshake; if (handshake.headers.cookie) { var str = handshake.headers.cookie; next(); } else { next(new Error('Missing Cookies')); } });
解决方案非常简单。它只是没有很好的记录。也可以通过如下所示的小型适配器将快速会话中间件用作Socket.IO中间件:
sio.use(function(socket, next) { sessionMiddleware(socket.request, socket.request.res, next); });
这是Express 4.x,Socket.IO 1.x和Redis的完整示例:
var express = require("express"); var Server = require("http").Server; var session = require("express-session"); var RedisStore = require("connect-redis")(session); var app = express(); var server = Server(app); var sio = require("socket.io")(server); var sessionMiddleware = session({ store: new RedisStore({}), // XXX redis server config secret: "keyboard cat", }); sio.use(function(socket, next) { sessionMiddleware(socket.request, socket.request.res || {}, next); }); app.use(sessionMiddleware); app.get("/", function(req, res){ req.session // Session object in a normal request }); sio.sockets.on("connection", function(socket) { socket.request.session // Now it's available from Socket.IO sockets too! Win! }); server.listen(8080);