【问题标题】:Is it possible to get an express session by sessionID?是否可以通过 sessionID 获得快速会话?
【发布时间】:2015-06-08 02:57:45
【问题描述】:

我有一个使用 express-session 的 NodeJS Express 应用程序。只要支持会话 cookie,这将非常有效。

不幸的是,它还需要与不支持任何类型 cookie 的 PhoneGap 应用程序一起使用。

我想知道:是否可以使用 sessionID 获得快速会话并访问该会话中的数据?

我想我可以将 sessionID 作为查询字符串参数附加到 PhoneGap 应用程序发送的每个请求,如下所示:

https://endpoint.com/dostuff?sessionID=whatever

但我不知道如何告诉 express 检索会话。

【问题讨论】:

  • 我不认为 express-session 支持除了 cookie 之外的任何东西,因为人们普遍认为现在每个人都在使用 cookie。你再也不会真正看到有人使用查询字符串来实现持久性,那是在九十年代。

标签: javascript node.js express express-session


【解决方案1】:

您当然可以创建一个快速路由/中间件来欺骗express-session 传入请求包含会话cookie。在会话中间件之前放置类似这样的东西:

app.use(function getSessionViaQuerystring(req, res, next) {
  var sessionId = req.query.sessionId;
  if (!sessionId) return res.send(401); // Or whatever

  // Trick the session middleware that you have the cookie;
  // Make sure you configure the cookie name, and set 'secure' to false
  // in https://github.com/expressjs/session#cookie-options
  req.cookies['connect.sid'] = req.query.sessionId;
  next();
});

【讨论】:

    【解决方案2】:

    在我的情况下,似乎 req.cookies 无法访问。这是另一种使用“x-connect.sid”标头重新创建会话的解决方案(如果您愿意,可以使用任何名称,甚至可以使用查询参数)。

    将此中间件放在会话中间件之后

    // FIRST you set up your default session like: app.use(session(options));
    
    // THEN you recreate it using your/custom session ID
    app.use(function(req, res, next){
        var sessionId = req.header('x-connect.sid');
    
        function makeNew(next){
            if (req.sessionStore){
                req.sessionStore.get(sessionId, function(err, session){
                    if (err){
                        console.error("error while restoring a session by id", err);
                    }
                    if (session){
                        req.sessionStore.createSession(req, session);
                    }
                    next();
                });
            } else {
                console.error("req.sessionStore isn't available");
              next();
            }
        }
    
        if (sessionId) {
            if (req.session){
                req.session.destroy(function(err){
                    if (err) {
                        console.error('error while destroying initial session', err);
                    }
                    makeNew(next);
                });
            } else {
                makeNew(next);
            }
        } else {
            next();
        }
    });

    【讨论】:

      猜你喜欢
      • 2018-02-28
      • 1970-01-01
      • 2021-12-28
      • 1970-01-01
      • 1970-01-01
      • 2011-05-19
      • 1970-01-01
      • 1970-01-01
      • 2018-10-30
      相关资源
      最近更新 更多