NodeJS 使用express/connect-redis在页面重新加载时抓取现有会话

snz8szmq  于 2023-06-05  发布在  Node.js
关注(0)|答案(2)|浏览(161)

使用connect、express和socket.io,我试图允许我的应用程序在重新连接时获取会话细节。我的会话显然在客户端连接时工作,但如果我在浏览器上刷新页面,它就会忘记所有内容。
我的会话cookie肯定是一样的,所以不是这样的。
我的代码是从许多不同来源获取的片段的大杂烩,因为似乎没有一个完整的示例应用程序。
我错过了什么?

var qs      = require('querystring'),
    express = require('express'),
    app     = express.createServer(),
    io      = require('socket.io').listen(app.listen(8000)),
    routes  = require('./routes'),
    pCookie = require('connect').utils.parseCookie,
    Session = require('connect').middleware.session.Session,
    RedStore= require('connect-redis')(express),
    sStore  = new RedStore();
   
// Configuration

app.configure(function(){
  app.set('views', __dirname + '/views');
  app.set('view engine', 'ejs');
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.cookieParser());
  app.use(express.session({ store: sStore, secret: 'tehsecretz' }));
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

app.configure('development', function(){
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure('production', function(){
  app.use(express.errorHandler());
});

// Routes

app.get('/', routes.index);

io.sockets.on('connection', function (client) {
    var hs = client.handshake,
        session = hs.session;

    console.log('A socket connected called: ' + hs.sessionId);

    var intervalId = setInterval(function() {
        hs.session.reload(function() {
            hs.session.touch().save();
        });
    }, 60 * 1000);

    if (!session.userName) {
        // Prompts the user for a name on the frontend
        client.emit('need-to-register');
    }

    client.on('message', function(msg, c) {
        console.log(session);
        console.log(msg);
    });

    client.on('register-user', function(data, fn) {
        // This retrieves the user's name
        // and - hopefully - saves it to the session.

        data = qs.parse(data);
        session.userName = data.username;

        hs.session.save();
        console.log('Saving: ', session);

        fn('ok');
    });

    client.on('disconnect', function() {
        clearInterval(intervalId);
    });
});

io.set('authorization', function (data, accept) {
    if (data.headers.cookie) {
        data.cookie = pCookie(data.headers.cookie);
        data.sessionId = data.cookie['connect.sid'];

        data.sessionStore = sStore;
        sStore.get(data.sessionId, function (err, session) {
            if (err || !session) {
                accept('Error', false);
            } else {
                console.log(data.sessionId, session);
                data.session = new Session(data, session);
                accept(null, true);
            }
        });
    } else {
        return accept('No cookie transmitted', false);
    }
});
sbtkgmzw

sbtkgmzw1#

所以在Daniel Baulig's post中,他引用了标识符sessionID。我认为这只是不好的约定(因为我习惯使用camelCase),并立即在代码中将其更改为sessionId
当我调试时,我在我的redis示例上打开了MONITOR ing,并注意到会话正在写入sess:undefined
原来sessionID是特殊的,在内部被引用为实际的标识符。将sessionId的所有示例更改为sessionID可以让我更好地了解谁正在连接!

hgncfbus

hgncfbus2#

在“express.session”中添加“cookie”

app.use(express.session({
    secret: 'exampleSecretKey'
    ,store: exampleStore
    ,key: 'example'
    cookie: {
        path: '/'
        ,expires: false // Alive Until Browser Exits
        ,httpOnly: true
    //  ,domain:'.example.com'
    }
});

相关问题