flash in node.js / express

 搭建环境

npm i connect-flash

How to use it 

Flash messages are stored in the session. 所以设置flash的第一步是设置session middleware.Then, use flash middleware provided by connect-flash. 这里session设置省略,可看另一篇文章:http://t.csdn.cn/xABkX

以及session存储在node.js里及其简单,几乎自动,具体案例:udemy sec48 express session.所以此处无需考虑具体储存。

const flash = require('connect-flash');
app.use(flash());

 doc 示例code

app.get('/flash', function(req, res){
  // Set a flash message by passing the key, followed by the value, to req.flash().
  req.flash('info', 'Flash is back!')
  res.redirect('/');
});
 
app.get('/', function(req, res){
  // Get an array of flash messages by passing the key to req.flash()
  res.render('index', { messages: req.flash('info') });
});

老师用下面code简化了每个render都要pass message。app.use()是不管传递什么页面都要经历的一个东西,所以在这里可以使得message平等的传递给每一个页面。所以,我们可以在boilerplate里加上对于message的传递 

app.use((req, res, next) => {
    res.locals.success = req.flash('success');
    res.locals.error = req.flash('error');
    next();
})

boilerplate.ejs 里<%- body %>前一行加入

<%- include('../partials/flash')  %>

flash.ejs (内含bootstrap 格式)

<% if(success && success.length) {%>
    <div class="alert alert-success alert-dimissible fade show" role="alert">
        <%= success %>
        <button type="button" class="close" data-dismiss="alert" aria-label="close">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>
    <% } %>

剩下就在需要flash的地方如doc所示flash就行

app.get('/flash', function(req, res){
  // Set a flash message by passing the key, followed by the value, to req.flash().
  req.flash('info', 'Flash is back!')
  res.redirect('/');
});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值