有可能通过sessionID获得快速会话吗

Is it possible to get an express session by sessionID?

本文关键字:会话 sessionID 有可能      更新时间:2023-09-26

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

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

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

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

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

但我不知道如何告诉express取回会话。

您当然可以创建一个快速路由/中间件,让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"标头重新创建会话的解决方案(如果愿意,可以使用任何名称,甚至可以使用查询参数)。

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

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