【问题标题】:flash messages are not saved before the page is rendered (node)在呈现页面之前不保存闪存消息(节点)
【发布时间】:2021-03-24 12:57:42
【问题描述】:

作为 express 应用程序中通用 get 路由的一部分,我想使用 express-session 和 connect-flash 发送两条 flash 消息。除了 req.flash 在页面呈现之前不保存之外,这一切都有效。因此,在用户再次加载另一个页面或相同页面之前,flash 消息不会显示。

路由中最后一个函数的代码:

    Post.countDocuments().exec(function(err, count){
        if(err) {
            console.log(err);
            res.redirect("back");
        }

        req.flash("success", ["It's working", "Hallelujah!"]);
        req.flash("error", ["Uh oh!", "We have a problem..."]);

        res.render("index", {posts: allPosts, dates: dates, current: pageNumber, pages: Math.ceil(count / pageLimit), showing: showing, total: count});
    });

以下是其中一个 Flash 消息模板 (ejs) 的代码:

    <div class="flash flash-success">
        <div class="flash-header">
            <span class="flash-title flash-title-success"><i class="fas fa-check"></i> <%= success[0] %></span>
            <span class="flash-close" onclick="return closeFlash(this);"><i class="fas fa-times"></i></span>
        </div>

        <hr class="flash-hr">
        <div class="flash-body-success"><%= success[1] %></div>
    </div>

我曾尝试在 req.flash 之后使用 .exec() 使渲染语句在完成时运行,但这不起作用,我还尝试了 req.session.save() 在回调中使用渲染语句,但是这也失败了。

去掉一个 req.flash 语句,也不能只传递一个字符串参数而不是两个数组。

【问题讨论】:

    标签: node.js express connect-flash


    【解决方案1】:

    问题是我有

    app.use(function(req, res, next) {
        res.locals.currentUser = req.user;
        res.locals.error = req.flash("error);
        res.locals.success = req.flash("success");
        return next();
    });
    

    在 app.js 中,所以这个中间件在路由有机会为 req.flash 设置值之前运行,这意味着错误和成功被设置为空。

    我通过在渲染页面之前创建一个函数来将 req.flash 保存在 res.locals 中解决了这个问题:

    var toolsObj = {};
    
    toolsObj.saveFlash = function(req, res) {
        res.locals.error = req.flash("error");
        res.locals.success = req.flash("success");
    };
    
    module.exports = toolsObj;
    

    【讨论】:

      猜你喜欢
      • 2015-12-26
      • 2011-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多