安装依赖中间件

1
2
3
npm install express-session --save
npm install connect-flash --save
npm install express-messages --save

Setting Options

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# Omit...
session = require 'express-session'
flash = require 'connect-flash'
app = express()
app.use cookieParser('keyboard cat')
app.use session({
cookie: maxAge: 60000
resave: true
saveUninitialized: true
secret: 'your secret'
})
app.use flash()
app.use (req, res, next) ->
res.locals.messages = require('express-messages')(req, res);
next();

Usage

1
2
3
4
5
6
7
8
9
# 在路由中使用
req.flash("success", "Email queued");
req.flash("error", "Email queued fail");
req.flash("warning", "Warning..");
# etc...
res.redirect('back')
# 在模板中呈现消息
!= messages()

Which will output the HTML:

1
2
3
4
5
6
7
8
9
<div id="messages">
<ul class="info">
<li>Email queued</li>
<li>Email sent</li>
</ul>
<ul class="error">
<li>Email delivery failed</li>
</ul>
</div>

自定义模板参考 Using a custom template