我是 NodeJS 的新手。我有一个问题,无法在我的 View 中显示 Flash 消息。 这是我的 Controller ,
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
对象会保留 session ,因此您需要在使用后将其清空,或者您可以简单地使用 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
将转义值输出到 View 中的语法。您需要做的就是将代码更改为:
<% if(flash && flash.err) { %>
<div class="alert alert-danger">
// Change <% to <%=
<%= flash.err %>
</div>
<% } %>
不需要 JSON.stringify,除非您喜欢引号。 请注意,我更改了 <%
至<%=
,在 EJS 中的意思是“转义并输出它”。它不是模板 HTML 或类似的东西,所以无论如何都可以转义它。
关于node.js - 无法使用 ejs 模板在 View 中显示 Flash 消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29593311/