搭建环境
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">×</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('/');
});