NodeJS,Socket IO会话和Express会话

时间:2016-12-19 21:43:14

标签: node.js express socket.io


我正在使用https://www.npmjs.com/package/express-socket.io-session在socket.io和express之间同步我的会话。
但是,当我通过socket.io设置会话时(使用socket.handshake.session.foo例如),我无法通过快递访问它:我得到了undefined req.session.foo。如何解决这个问题?有什么问题?
这是:我的app.js代码:

// Requires

global.config = require("./config.js");
var express   = require("express");
var session   = require("express-session");
global.sha1   = require("sha1");
global.moment = require("moment");
var rhandler  = require("./handler.js");
global.mySQL  = require("./mysql.js");
var entities  = new require("html-entities").XmlEntities;
global.Users  = {};

var app        = express();
var server     = require("http").createServer(app).listen(config.server.port);
global.Handler = new rhandler();

app.set("view engine", "ejs");
app.use("/assets", express.static("public"));

var socketIO = require("socket.io");
var io       = socketIO.listen(server);

var session = require("express-session")({
    secret: config.express.secret,
    resave: true,
    saveUninitialized: true
});
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
}));

io.sockets.on("connection", function(socket) {
    socket.on("login", function(obj, callback) {
        socket.handshake.session.test = "test";
    });
});

app.get("/", function(req, res) {
    console.log(req.session.test);
    res.end();
});

1 个答案:

答案 0 :(得分:0)

让我的评论得到答案,因为它解决了你的问题。

根据文档,您应该访问socket.handshake.session.foo,而不是socket.handshake.foo

并且,为了保留对会话的修改,我发现您需要在修改会话后添加socket.handshake.session.save()