express 版本更新后遇到的问题 flash()
发布于 3年前 作者 papaivan 3199 次浏览

首先发一个

原先的express 2.X中提供的API flash();

我找到一个关于修改的说明 req.flash() (just use sessions: req.session.messages = [‘foo’] or similar)

请问这个API原先的用途是什么?

2 回复
/**
 * Queue flash `msg` of the given `type`.
 *
 * Examples:
 *
 *      req.flash('info', 'email sent');
 *      req.flash('error', 'email delivery failed');
 *      req.flash('info', 'email re-sent');
 *      // => 2
 *
 *      req.flash('info');
 *      // => ['email sent', 'email re-sent']
 *
 *      req.flash('info');
 *      // => []
 *
 *      req.flash();
 *      // => { error: ['email delivery failed'], info: [] }
 *
 * Formatting:
 *
 * Flash notifications also support arbitrary formatting support.
 * For example you may pass variable arguments to `req.flash()`
 * and use the %s specifier to be replaced by the associated argument:
 *
 *     req.flash('info', 'email has been sent to %s.', userName);
 *
 * To add custom formatters use the `exports.flashFormatters` object.
 *
 * @param {String} type
 * @param {String} msg
 * @return {Array|Object|Number}
 * @api public
 */

req.flash = function(type, msg){
  if (this.session === undefined) throw Error('req.flash() requires sessions');
  var msgs = this.session.flash = this.session.flash || {};
  if (type && msg) {
    var i = 2
      , args = arguments
      , formatters = this.app.flashFormatters || {};
    formatters.__proto__ = flashFormatters;
    msg = utils.miniMarkdown(msg);
    msg = msg.replace(/%([a-zA-Z])/g, function(_, format){
      var formatter = formatters[format];
      if (formatter) return formatter(utils.escape(args[i++]));
    });
    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;
  }
};

自己猜

Migrating from 2.x to 3.x

req.flash() (just use sessions: req.session.messages = [‘foo’] or similar) connect-flash can be used as middleware to provide req.flash()

需要安装 npm install connect-flash 在app.js中加入 var flash = require(‘connect-flash’); app.use(flash());

这样就能继续用 req.flash()

回到顶部