【问题标题】:Can't get connect-flash to work with express.js on redirect无法让 connect-flash 在重定向时与 express.js 一起使用
【发布时间】:2013-02-17 23:23:46
【问题描述】:

好的,由于某种原因,当我res.render() 时会话闪存工作,但是当我尝试设置会话闪存然后重定向时,它不显示。问题出在else子句中的联系方式下面)...

这是重定向期间记录到控制台的内容:

{} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} { info: [ 'Thanks we will return your message soon' ] } {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {}

如您所见,消息肯定在其中,但看起来它正在被一个空对象替换。

这是我的代码:

app.js

var flash = require('connect-flash');

// Grab sessions
var sessionFlash = function(req, res, next) {
  res.locals.messages = req.flash();
  console.log(res.locals.messages);
  next();
}

app.configure(function() {
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(viewHelpers());
  app.use(express.bodyParser({ uploadDir : './' }));

  app.use(expressValidator);
  app.use(express.methodOverride());

  app.use(express.cookieParser('keyboard cat'));
  app.use(express.session({
    secret: config.secret,
    cookie: {
      maxAge: 365 * 24 * 60 * 60 * 1000
    },
    store: new MongoStore(config.db)
  }));

  app.use(flash());
  app.use(sessionFlash);

  app.use(express.static(__dirname + '/public'));
  app.use(app.router);
});

views/layout.jade

- if (typeof message !== 'undefined')
  =message

controllers/index.js

function controllers(params) {

  controllers.contact = function(req, res) {
    if (errors) {
      // This works as intended
      req.flash('info', 'Please fix the errors below.');

      res.render('contact', {
        title : 'Contact -',
        message: req.flash('info'),
        errors: errors,
        params: params
      });
      return;
    } else {
      // This doesn't work
      req.flash('info', 'Thanks we will return your message soon');
      res.redirect('/');
    }
   };
   return controllers
  }

  module.exports = controllers;

【问题讨论】:

  • 我也遇到了这个问题。我有一个req.get('/'),如果我在use.flash 之前调用我的路线,我会收到req.flash is not a function 错误。通过记录req.path,似乎大多数请求都是针对静态文件的,并且闪存消息被发送到其中一个。你找到解决方案了吗?

标签: javascript node.js express


【解决方案1】:

好吧,您正在重定向到“/”,服务器没有响应。

您的 app.js 中没有 app.get('/', function(req, res){...});

Flash 消息是在来自同一客户端的两个请求之间的持续时间内存储在服务器上的消息,因此仅在下一个请求中可用。闪光灯没有显示,因为您的res.redirect('/'); 什么都不做。

【讨论】:

  • 这就是我在 app.config 中有 app.use(sessionflash) 的部分原因,因为我希望在每个 Web 请求上都能看到它(因为它会吐出会话中闪烁的任何内容)。
  • 顺便说一句,我确实有 app.get('/'),​​它位于另一个路由文件中,我将其导出到 app.js,但这并不重要,因为所有路由都应该达到 @987654324 @middleware 我在之前的评论中提到过。看看我发布的日志——它在里面,只是被覆盖了。
  • 像 '/' 这样的路由需要 app.use(app.router);并且必须在 app.use(flash()); 之前否则,如果它工作正常,可能是您的“/”页面忽略了 Flash 消息。
猜你喜欢
  • 1970-01-01
  • 2014-06-20
  • 2016-12-28
  • 2015-12-31
  • 2014-06-08
  • 2017-06-24
  • 1970-01-01
  • 1970-01-01
  • 2015-03-20
相关资源
最近更新 更多