我正在构建基于套接字的Web应用程序。用户登录后,我将其数据保存到session (express-session)
。现在的问题是,当用户打开房间时,将调用socket send,并且在服务器端没有请求数据,因为我需要在打开房间之前检查用户ID。下面是我的代码。
server.js
const session = require('express-session');
app.use(session({
key: 'userid',
secret: 'zxcvasd',
resave: false,
saveUninitialized: false,
cookie: {
expires: 6000000
}
}));
const socketCtrl = require('../controllers/socket.controller');
socket.on('open-broadcast', function (broadcastId) {
socketCtrl.setBroadcastData(broadcastId);
});
socket.controller.js
exports.setBroadcastData = (broadcastId) => {
// here I want session data like below
// const user = req.session.user
};
答案 0 :(得分:1)
您可以像这样为您的快速会话添加中间件 使用this npm程序包
var ios = require('socket.io-express-session');
var io = require("socket.io")(server);
io.use(ios(Session));
var sess = socket.handshake.session;
sess.userId