无法使用 ejs 模板在视图中显示 flash 消息

Unable to display flash message in view with ejs template

我是 NodeJS 的新手。我有一个问题,我无法在我的视图中显示 flash 消息。 这是我的控制器,

index : function(req, res){
    res.locals.flash = _.clone(req.session.flash);
    res.locals.layout = false;
    res.view('login');
},
login : function(req, res){

       ....

        if(!admin){
            req.session.flash = {
                err : 'User is not found.' // My flash message
            }
            res.locals.layout = false;
            res.redirect('login'); 
            return;
        }

      .....
}

这是我的看法,

    <% if(flash && flash.err) { %>
    <div class="alert alert-danger">
    <% JSON.stringify(flash.err) %>
    </div>
    <% } %>   

当登录为假时,它只显示一个空的警告框。 我还有第二个问题。当我刷新页面时,警告框并没有消失。

有人可以帮助我吗? 非常感谢。

警告框不断出现,因为 req.session.flash 对象保留了会话,因此您需要在使用后将其清空,或者您可以简单地使用 req.flash(),这样做是为了你。因此,将您的 index 方法更改为如下内容:

index: function(req, res) {
    // req.flash() returns the contents of req.session.flash and flushes it
    // so it doesn't appear on next page load. No need to clone.
    res.locals.flash = req.flash();
    res.locals.layout = false;
    res.view('login');
},

现在,进入第二个问题。错误消息没有出现,因为您没有使用正确的 EJS 语法将转义值输出到视图中。您需要做的就是将您的代码更改为:

<% if(flash && flash.err) { %>
    <div class="alert alert-danger">
        // Change <% to <%=
        <%= flash.err %>
    </div>
<% } %> 

无需 JSON.stringify,除非您喜欢引号。 请注意,我将 <% 更改为 <%=,这在 EJS 中表示 "escape this and output it"。它不是模板 HTML 或类似的东西,所以无论如何都可以转义它。