【问题标题】:What's the best way to handle Node.js flash messages?处理 Node.js 闪存消息的最佳方式是什么?
【发布时间】:2014-12-19 00:32:50
【问题描述】:

我是 Node.js 的初学者,我非常喜欢它。我想知道如何以最好和最简单的方式处理 Flash 消息。

我在我的站点中使用了 connect-flash 包。有更好的吗?

我总是将我的 flash 消息放在我的渲染函数中,如下所示:

res.render('auth/login', {
        title: 'Log in',
        success: req.flash('success'),
        error: req.flash('error')
    });

它有办法在全球范围内处理吗?像 res.locals.messages 变量或类似的东西?

我使用 JADE html 模板,所以我像 #{success} 一样打印它们。如何以这种方式访问​​全局变量来打印我的 Flash 消息?

非常感谢您的帮助和建议!

【问题讨论】:

    标签: node.js express pug flash-message connect-flash


    【解决方案1】:

    如果你想在每个请求中设置successerror 变量,你可以像你提到的那样使用res.locals。您可以使用在connect-flash 之后包含的中间件来完成此操作:

    // ...
    
    app.use(function(req, res, next) {
      res.locals.success = req.flash('success');
      res.locals.error = req.flash('error');
      next();
    });
    
    // ...
    

    现在,successerror 将始终出现在对 res.render 的每次调用中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-24
      • 1970-01-01
      • 1970-01-01
      • 2021-07-22
      • 1970-01-01
      • 1970-01-01
      • 2022-01-11
      • 2013-09-11
      相关资源
      最近更新 更多