我正在使用express-socket.io-session
和express-mysql-session
分享socket.io
和express
之间的会话。我这样做如下:
var express = require('express');
var mysql = require('mysql');
var app = express();
var serv = require('http').Server(app);
var io = require('socket.io')(serv, {});
var MySQLStore = require('express-mysql-session');
var options = {
host: "...",
user: "...",
password: "...",
database: "...",
};
var con = mysql.createConnection(options);
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
var sessionStore = new MySQLStore({},con);
var session = require("express-session")({
secret: "...",
resave: true,
saveUninitialized: true,
store : sessionStore
});
var sharedsession = require("express-socket.io-session");
// Use express-session middleware for express
app.use(session);
// Use shared session middleware for socket.io
// setting autoSave:true
io.use(sharedsession(session, {
autoSave:true
}));
接下来,我有以下内容:
app.get('/', function(req, res, next){
console.log(req.session.sessionId);
console.log(req.session.username);
});
最后:
socket.on('login', function(data) {
socket.handshake.session.sessionId = sessionId;
socket.handshake.session.username = result[0].username;
socket.handshake.session.save();
}
检查数据库时,这些值会正确保存。然而,
console.log(req.session.sessionId);
console.log(req.session.username);
即使在登录发生后也始终打印undefined
。