【问题标题】:Shared sessions (Express.js, Socket.io, Passport.js)共享会话(Express.js、Socket.io、Passport.js)
【发布时间】:2016-09-10 22:21:08
【问题描述】:

在与 Passport.js 成功连接后,我正在尝试检索用户数据。

我使用 express-session 和 express-socket.io-session 来共享数据。这是我的代码的一部分:

var expressSession   = require('express-session');
var sharedsession    = require("express-socket.io-session");
var MongoStore       = require('connect-mongo')(expressSession);
var sessionStore     = new MongoStore({ 
    url: 'mongodb://127.0.0.1:27017/default',
    ttl: 24 * 60 * 60 // = 1 day
});

var session = expressSession({
    cookie: cookieParser,
    secret: 'mySecret',
    resave: false,
    saveUninitialized: false,
    store: sessionStore,
});

app.use(session);
app.use(passport.initialize());
app.use(passport.session());

io.use(sharedsession(session, {
    autosave: true
}))
require('./app/socket-io.js')(io);

这是我尝试保存一些数据的地方 (req.session.test)。

app.get( '/index.html', isLoggedIn, function( req, res ) {
    req.session.test = 'Hello World !';
    console.log('=====');
    console.log(req.sessionID);
    console.log(req.session);
    res.sendFile( root + '/index.html' );
});

我注意到 app.get() 中的 req.sessionID 与 io.on('connection, function(...)) 中的 client.request.sessionID 不同。根据此线程中的 cmets,这可能很重要:How to share sessions with Socket.IO 1.x and Express 4.x?

我很乐意提供任何帮助! :)

【问题讨论】:

    标签: node.js express socket.io passport.js


    【解决方案1】:

    实际上,这是一个 CORS 问题。

    在客户端,我通过以下方式连接到 socket.io:

    var socket = io.connect("127.0.0.1"); // with the server ip
    

    这触发了跨域请求,并限制了 passport.socketio (https://github.com/jfromaniello/passport.socketio) 的行为。查看“CORS-Workaround”部分了解更多信息。

    然后,解决方案就是遵循“解决方法”:

    var socket = io.connect('//' + window.location.host);
    

    【讨论】:

      猜你喜欢
      • 2013-02-12
      • 1970-01-01
      • 2018-05-30
      • 1970-01-01
      • 1970-01-01
      • 2012-08-03
      • 2012-08-20
      • 2018-05-18
      • 2021-02-06
      相关资源
      最近更新 更多