【问题标题】:Display flash message from router to a ejs view显示从路由器到 ejs 视图的 flash 消息
【发布时间】:2019-06-29 07:17:07
【问题描述】:

我正在设置当消息从路由器发送到视图时显示在视图上的 flash 消息

if (err) {
            console.log(err);
         } else {
            req.flash('success', 'You are now registered and can Log in')
            res.redirect('/users/login');
            // res.render('users/login',{
            //    success_message:'Account created successfully'
            // });
         }

有没有一种方法可以在页面加载时将其显示在视图上,而不必像评论的那样手动执行此操作,因为该方法有效,但我希望自动显示它。我检查了论坛上的一些提交,但我仍然无法找到真正显示消息的提交

【问题讨论】:

    标签: node.js mongodb express ejs


    【解决方案1】:

    connect-flash 用于存储消息的会话。

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

    在 express js 中使用中间件

    app.use(flash());
    

    在请求渲染中附加 flash 消息

    res.render('/users/login', { message: req.flash('Restistration succesfully.') });
    

    在 html/ejs 中显示 flash 消息

    <% if (message.length > 0) { %>
       <div class="alert alert-danger"><%= message %></div>
     <% } %>
    

    【讨论】:

    • 我打算在执行res.redirect 而不是res.render 时显示闪存错误。您的解决方案有效,但它不在我想要的上下文中
    • 试试这个 req.flash('success', 'Restistration succesfully.'); res.redirect('/users/login');根据文件
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-13
    • 1970-01-01
    • 1970-01-01
    • 2017-02-07
    • 1970-01-01
    • 1970-01-01
    • 2013-07-05
    相关资源
    最近更新 更多