分享会话Socket.io Express

时间:2018-06-13 11:56:13

标签: node.js express session socket.io

我正在使用express-socket.io-sessionexpress-mysql-session分享socket.ioexpress之间的会话。我这样做如下:

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

0 个答案:

没有答案