是否可以通过 sessionID 获得快速会话?

Is it possible to get an express session by sessionID?

我有一个使用快速会话的 NodeJS Express 应用程序。这很好用,只要支持会话 cookie。

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

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

我想我可以像这样为 PhoneGap 应用程序发送的每个请求附加 sessionID 作为查询字符串参数:

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

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

您当然可以创建一个 express route/middleware 来欺骗 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();
});

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

将这个中间件放在session中间件

之后

// 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();
    }
});