install
npm install connect-flash
app.js
var session = require('express-session');
var flash = require('connect-flash');
var app = express();
app.use(session({
secret:'dfdfdfdfsfsfsfsfs',
resave: false,
saveUninitialized: true
}));
app.use(flash());
app.get('/', function(req, res){
res.render('index', { message: req.flash('info') });
});
app.get('/flash', function(req, res){
req.flash('info', 'Hi there!')
res.redirect('/');
});
app.get('/no-flash', function(req, res){
res.redirect('/');
});
app.get('/multiple-flash', function(req, res){
req.flash('info', ['Welcome', 'Please Enjoy']);
res.redirect('/');
});
index.ejs
<!DOCTYPE html>
<html>
<head>
<title>connect-flash</title>
</head>
<body>
<p>
<a href="/flash">Flash</a> |
<a href="/no-flash">No Flash</a>
</p>
<% if (message) { %>
<p><%= message %></p>
<% } %>
</body>
</html>
参考资料:
https://www.npmjs.com/package/connect-flash