express中connect-flash中间件的使用
在學習node的時候,flash是困擾我最久的一個中間件,之前一直都沒有很好的理解,這里做一個總結。
參考自:http://yunkus.com/connect-flash-usage/
?
什么是flash?
The flash is a special area of the session used for storing messages. Messages are written to the flash and cleared after being displayed to the user. The flash is typically used in combination with redirects, ensuring that the message is available to the next page that is to be rendered.
flash是配合session使用的,所以在使用flash之前,要引入express-session模塊,它往往用在登錄和注冊,消息只會通知一次就消失了,其中redirect和flash是不能分開使用的。
?
安裝與配置
即通過npm安裝 express-session模塊 和 connect-flash模塊 即可。
配置app.js文件如下:
var settings = require('./settings'); //配置信息 var flash = require('connect-flash'); var session = require('express-session'); app.use(session({secret: settings.cookieSecret, //加密key: settings.db, //cookie namcookie: {maxAge: 60000},resave: false,saveUninitialized: true, })); app.use(flash()); // set flash app.use(function (req, res, next) {res.locals.errors = req.flash('error');res.locals.infos = req.flash('info');next(); });注意:上面定義locals對象下變量的時候一定要有next()向下傳遞,否則生產線就會停止?!?/p>
另外,settings信息是必須配置的,這樣更容易維護:
module.exports = {cookieSecret: 'orders',db: 'ordersdb',host: 'localhost',port: 27017 }?
?
如何使用
// 登錄 router.get('/login', function(req, res, next) {res.render('login', { title: '歡迎登錄' }); }); router.post('/login', function(req, res, next) {User.get(req.body.username,function(err,user){if(!user || user.name === ''){req.flash('error','用戶不存在');return res.redirect('login');}if(req.body.password != user.password){req.flash('error','密碼不對');return res.redirect('login');}req.flash('info','登錄成功');res.redirect('login');}) });
上面我以登錄的路由代碼作為例子,一看就懂,只需要在要顯示信息的地方添加形如:req.flash('error','用戶不存在');的代碼就可以了。那怎么才能在頁面中調用這些提示信息呢?我們接著往下看。下面是一個簡單的調用例子,但也足以把問題說明白了。
?
<div class="wrap"> <div class="wrap-left"><ul><li><a href="/">主頁</a></li><li><a href="/login">登錄</a></li><li><a href="/reg">注冊</a></li></ul> </div> <div class="wrap-right"><h1><%= title %></h1><div class="wrap-content"><form method="post"><ul><li>用戶名:<input type="text" name="username"></li><li>密碼:<input type="text" name="password"></li><li><button>登錄</button></li><li><%= errors %></li></ul></form> </div> </div> </div>?
代碼中的<%= errors %>就是調用相應的信息的方法,為什么要這樣寫呢?為什么里面的一個 errors,而不是 我們在 index.js 中寫的req.flash('error','用戶不存在');中的 error 變量呢?這個你看看我們一開始在 app.js 中的配置代碼你就明白了。我們已經把req.flash('error');的提示信息賦值給了res.locals.errors,而我們如果要調用locals 中的 errors 變量,不需要寫成locals.errors,而是直接寫變量名 errors 就可以了。
conncet-flash 模塊的用法就給大家分享到這里了,這里只給你一個實現的思路,并不會給你一個面包,但你可以通過這個思路做一個美味的面包。人人都討厭伸手黨,總想著天上掉面包,不如自己去做面包,人必自救,而后人救之。
?
<h5 class="text-center"><%= success %></h5><h5 class="text-center"><%= error %></h5>?
?
?
?
結束
轉載于:https://www.cnblogs.com/zhuzhenwei918/p/6785259.html
總結
以上是生活随笔為你收集整理的express中connect-flash中间件的使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 心遇是诈骗软件吗
- 下一篇: Cocos2d-x3.1FileUtil