gpt4 book ai didi

node.js - 如何与 Socket.IO 1.x 和 Express 4.x 共享 session ?

转载 作者:IT老高 更新时间:2023-10-28 21:49:04 25 4
gpt4 key购买 nike

如何与 Socket.io 1.0 和 Express 4.x 共享 session ?我使用 Redis Store,但我相信这不重要。我知道我必须使用中间件来查看 cookie 并获取 session ,但不知道如何。我搜索但找不到任何工作

    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'));
}
});

最佳答案

解决方案非常简单。它只是没有很好的记录。也可以将 express session 中间件用作 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);

关于node.js - 如何与 Socket.IO 1.x 和 Express 4.x 共享 session ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25532692/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com