express.js解析cookies?

时间:2015-06-26 02:06:05

标签: javascript node.js cookies express

我正在尝试使用旧的库balloons.io作为聊天应用程序的基础,但它已经过时了,在这个特定的代码中,我试图弄清楚如何使用express 4x来解析cookie以获得一个sid没有从req.session

获取它

由于快递4x不再使用connect,我该如何做以下类似的事情,但是在新的快递版本中呢?

/*
 * Module dependencies
 */

var sio = require('socket.io')
  , parseCookies = require('connect').utils.parseSignedCookies
  , cookie = require('cookie')
  , fs = require('fs');

/**
 * Expose Sockets initialization
 */

module.exports = Sockets;

/**
 * Socket.io
 *
 * @param {Express} app `Express` instance.
 * @param {HTTPServer} server `http` server instance.
 * @api public
 */

function Sockets (app, server) {
  var config = app.get('config');
  var client = app.get('redisClient');
  var sessionStore = app.get('sessionStore');

  var io = sio.listen(server);
  io.set('authorization', function (hsData, accept) {
    if(hsData.headers.cookie) {
      var cookies = parseCookies(cookie.parse(hsData.headers.cookie), config.session.secret)
        , sid = cookies['balloons'];

      sessionStore.load(sid, function(err, session) {
        if(err || !session) {
          return accept('Error retrieving session!', false);
        }

        hsData.balloons = {
          user: session.passport.user,
          room: /\/(?:([^\/]+?))\/?$/g.exec(hsData.headers.referer)[1]
        };

        return accept(null, true);

      });
    } else {
      return accept('No cookie transmitted.', false);
    }
  });

  });

};

2 个答案:

答案 0 :(得分:0)

不确定这是否有帮助,但明确4.x中的Cookie解析已被解压缩到cookie-parser包。我不确定,但您可以将connect.util.parseSignedCookies换成cookieParser.parseSignedCookies`。

关于我可以帮助你的所有内容,因为我还没有使用过socket.io。

答案 1 :(得分:0)

function Sockets (app, server, pub, sub, sessionStore) {
  var config = app.get('config');
  var secrets = require('./config/secrets');
  var client = pub;

  var io = sio.listen(server);
  io.set('authorization', function (handshake, callback) {

    if(handshake.headers.cookie) {

      // pay attention here, this is how you parse, make sure you use
      // cookie-parser and cookie
      var cookies = cookie.parse(handshake.headers.cookie);
      var sid = cookieParser.signedCookie(cookies['balloons'], secrets.sessionSecret);

      // get the session data from the session store
      sessionStore.load(sid, function(err, session) {
        if(err || !session) {
          return callback('Error retrieving session!', false);
        }

        // this is not storing the data into the handshake object
        handshake.headers.xygaming = {
          user: session.passport.user,
          room: /\/(?:([^\/]+?))\/?$/g.exec(handshake.headers.referer)[1]
        };

        return callback(null, true);

      });

    } else {
      return callback('No cookie transmitted.', false);
    }
  });

}