在Express.js中,如何使模板显示flash消息

In Express.js, how do I make my template display the flash messages?

本文关键字:显示 flash 消息 何使模 Express js      更新时间:2023-09-26
app.get('/',function(req,res){
    res.render('home'); // I want the template to be able to access the flash message..
});
app.get('/go',function(req,res){
    req.flash("info", "You went GO, and got redirected to home!");
    res.redirect('/');
});

用户首先转到"/go"。之后,他将被重定向到"/",我想要一条闪烁消息显示为javascript警报。

我该怎么做?

将其作为本地添加到要渲染的调用中:

res.render("home", {info: req.flash("info")});

并在您的模板中使用它:

#flash
  p= info

您可以使用express动态助手来简化您的生活。

app.dynamicHelpers({flashMessages: function(req, res) {
var html = ""
  , flash  = req.flash();
['error', 'info'].forEach(function(type) {
  if(flash[type]) {
    flash[type].forEach(function(message) {
      html += "<div class='alert " + type + "'>" + message + "</div>";
    });
  }
});
return html; }});

并且在您的布局中(ejs示例(

  <body><%- flashMessages %><%- body %></body>
app.dynamicHelpers({flash: function(req, res){return req.flash();}});

现在,您可以访问视图中的flash对象。您的逻辑中没有HTML,也不需要在每条路由中添加所有参数。

对我来说,我使用以下代码来显示闪烁消息:

app.js

app.use(function (req, res, next) {
 req.session.message = req.session.message || { error: [], success: [], info: [] };
 app.locals.message  = req.session.message;
}

user.js路由中:

app.post('/users/new', function (req, res, next) {
    //...
    // do some work
    req.session.message.info.push('Account created successfully');
    res.redirect('/login');
});

然后,在视图中创建一个message.jade,您可以将其包含在其他视图中:

消息中。翡翠

- var i
- if (message.error && message.error.length)
  .alert.alert-warning.alert-dismissable
    button.close(type="button", data-dismiss="alert", aria-hidden="true") &times;
    - for (i = 0; i < message.error.length; i++)
      .center!= message.error[i]
- if (message.info && message.info.length)
  .alert.alert-info.alert-dismissable
    button.close(type="button", data-dismiss="alert", aria-hidden="true") &times;
    - for (i = 0; i < message.info.length; i++)
      .center!= message.info[i]
- message.info = message.error = [] // REMEMBER to reset messages to an empty array

也有类似的问题,解决方案似乎是:

req.flash('error', 'validation failed');
res.redirect('back');

使用back似乎可以维护flash消息,因为重定向到相同的路由会丢失它。

如果您使用的是Express 3,则内置的闪存功能已被删除。要获得相同的功能,您需要安装connect-flash模块,然后在初始化会话之后和app.use(app.router);之前添加来自此Gist的代码:https://gist.github.com/3070950