Express 连接闪存会话对象来自何处

Express 连接闪存会话对象来自何处,express,connect,Express,Connect,我正在我的express应用程序中使用消息警报中间件connect flash。我可以在github上找到此中间件。 当我查看connect flash源代码时,我真的不知道this.session对象来自哪里。考虑连接闪速源代码: module.exports = function flash(options) { options = options || {}; var safe = (options.unsafe === undefined) ? true : !options.u

我正在我的express应用程序中使用消息警报中间件connect flash。我可以在github上找到此中间件。
当我查看connect flash源代码时,我真的不知道this.session对象来自哪里。考虑连接闪速源代码:

module.exports = function flash(options) {
  options = options || {};
  var safe = (options.unsafe === undefined) ? true : !options.unsafe;

  return function(req, res, next) {
    if (req.flash && safe) { return next(); }
    req.flash = _flash;
    next();
  }
}

function _flash(type, msg) {
  if (this.session === undefined) throw Error('req.flash() requires sessions');
  var msgs = this.session.flash = this.session.flash || {};
  if (type && msg) {
    // util.format is available in Node.js 0.6+
    if (arguments.length > 2 && format) {
      var args = Array.prototype.slice.call(arguments, 1);
      msg = format.apply(undefined, args);
    } else if (isArray(msg)) {
      msg.forEach(function(val){
        (msgs[type] = msgs[type] || []).push(val);
      });
      return msgs[type].length;
    }
    return (msgs[type] = msgs[type] || []).push(msg);
  } else if (type) {
    var arr = msgs[type];
    delete msgs[type];
    return arr || [];
  } else {
    this.session.flash = {};
    return msgs;
  }
}
要在express中实现,我必须在app.configure块中包含。考虑代码

app.configure(function () {
        //Other middleware
        app.use(function (req, res, next) {
            console.log(this.session);
            next();
        });
        app.use(flash());
看看我的自定义中间件,当我显示this.session对象时,我得到了“undefined”。为什么这个.session在connectflash中工作,我在这里得到session对象,但在我的中间件中没有。创建中间件的回调模式完全相同

(function (req, res, next) {
        //Code
         next();
}

会话对象由会话中间件添加。如果
req.session
未定义,您要么没有定义会话中间件,要么在您期望的中间件之后定义它

明确的

  • 会话中间件
  • 自定义中间件:定义了req.session
未定义

  • 自定义中间件:req.session未定义,因为对象稍后添加
  • 会话中间件
因此,我猜想您是在
express.session
之后定义了flash中间件,但您的自定义中间件是在
express.session
之前定义的


因为express只是一个函数数组(中间件),它对请求进行填充并返回响应,这意味着定义这些函数的顺序很重要。

会话对象是由会话中间件添加的。如果
req.session
未定义,您要么没有定义会话中间件,要么在您期望的中间件之后定义它

明确的

  • 会话中间件
  • 自定义中间件:定义了req.session
未定义

  • 自定义中间件:req.session未定义,因为对象稍后添加
  • 会话中间件
因此,我猜想您是在
express.session
之后定义了flash中间件,但您的自定义中间件是在
express.session
之前定义的

因为express只是一个函数数组(中间件),它对请求进行填充并返回响应,这意味着定义这些函数的顺序很重要