gpt4 book ai didi

node.js - 如何在 socket.io 连接中获取持久的快速 session ID?

转载 作者:行者123 更新时间:2023-12-04 01:40:21 24 4
gpt4 key购买 nike

我正在构建一个 MEAN 堆栈聊天应用程序。我希望能够在连接处理程序上的 socket.io 中获得快速 session ID。我可以访问 socket.handshake.session.id 但它与 req.session.id 不同。进一步 socket.handshake.session.id 在每个套接字上不断变化。

我试图通过查找 connect.sid key 从 req.handshake.cookie 获取 session ID 来解决此问题,但该 key 未在其中定义。

const cors = require('cors'),
express = require('express'),
eSession = require('express-session'),
cookieParser = require('cookie-parser'),
MongoStore = require('connect-mongo')(eSession),
sharedsession = require('express-socket.io-session'),
http = require('http'),
bodyParser = require('body-parser'),
socketio = require('socket.io');

const app = express();
const server = http.createServer(app);
const io = socketio(server);

const port = process.env.PORT || 3000;
//imports
const mongoose = require('./config/dbconnection');

//routes
const user = require('./api/routes/user');

const socketHandle = (io, mStore) => {
io.on('connection', (socket) => {
socket.on('join', (options, callback) => {

console.log(socket.handshake.headers.cookie); //no connect.sid string present
console.log(socket.handshake.session.id) // has value but keeps changing on each io connection and this id is not the same as req.session.id in an api endpoint method

});
});

const corsOptions = {
origin: 'http://localhost:4200',
optionsSuccessStatus: 200
};

const db = mongoose.connection;
const mStore = new MongoStore({ mongooseConnection: db });
const session = eSession({
secret: 'my-secret',
resave: true,
saveUninitialized: true,
store: mStore
});

app.use(cookieParser('my-secret'));
app.use(session);
io.use(sharedsession(session,{autoSave:true}));

socketHandle(io, mStore);

//body-parser
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.use(cors(corsOptions));

app.use('/user', user);

server.listen(port, () => console.log(`listening on http://localhost:${port}`));

socket.handshake.session.id 和 socket.handshake.headers.cookie(connect.sid key) 都应该提供与 req.session.id 具有相同值的 session ID

最佳答案

@Anand Kashyap 是正确的,如果您让 express 服务器为您的客户端提供服务,cookie 将会存在。

但是,当您的客户端位于不同的主机上时,您需要将 withCredentials: true 传递给套接字的构造函数。这会将 cookie 附加到请求, session 将正常工作。

const io = require("socket.io-client");

const socket = io("ws://example.com/", {
withCredentials: true,
autoConnect: 10000
});

关于node.js - 如何在 socket.io 连接中获取持久的快速 session ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57726457/

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