将flash连接到会话对象的位置

时间:2013-08-09 12:19:52

标签: express connect

我在我的快递应用程序中使用消息提醒中间件connect-flash。我可以在github上找到这个中间件https://github.com/jaredhanson/connect-flash 当我看看connect-flash源代码时,我真的不知道,this.session对象来自哪里。考虑connect-flash源代码:

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对象时,我得到了“未定义”。为什么连接闪存中的this.session工作,我得到了会话对象,但不是我的中间件。用于创建中间件的回调模式完全相同

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

1 个答案:

答案 0 :(得分:1)

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

定义

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

未定义

  • 自定义中间件:req.session未定义,因为稍后会添加该对象。
  • 会话中间件

所以我的猜测是你在express.session之后定义了flash中间件,但你的自定义中间件是在express.session之前定义的。

由于express只是一个函数数组(中间件),它对请求执行操作并返回响应意味着您定义这些函数的顺序很重要。

相关问题