在app.js里用
app.use(function (req, res, next) { res.locals.error= req.flash('error').length ? req.flash('error') : null; next(); });
前端(如template.ejs)文件调用时用
<% if(locals.error) { %>
<%= locals.error %>
<% } %
不会输出任何东西
原因是req.flash('error')执行一次就会消失。 所以在执行过req.flash('error').length这句话后req.flash('error')的内容已经消失就不会赋值给res.locals.error,在前端也就不会显示。
解决办法是先把req.flash('error')用变量存下来
app.use(function (req, res, next) { //req.flash('error');只执行一次,随后消失,所以要先保存进变量 var err = req.flash('error'); res.locals.error = err.length ? err : null; next(); });