中跃建设集团网站,免费网页游戏大全,dw做网站弊端,正规网站建设公司哪家好在学习node的时候#xff0c;flash是困扰我最久的一个中间件#xff0c;之前一直都没有很好的理解#xff0c;这里做一个总结。 参考自#xff1a;http://yunkus.com/connect-flash-usage/ 什么是flash#xff1f; The flash is a special area of the session used for s… 在学习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()向下传递否则生产线就会停止。 另外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 classwrap
div classwrap-leftullia href/主页/a/lilia href/login登录/a/lilia href/reg注册/a/li/ul
/div
div classwrap-righth1% title %/h1div classwrap-contentform methodpostulli用户名input typetext nameusername/lili密码input typetext namepassword/lilibutton登录/button/lili% 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 classtext-center% success %/h5h5 classtext-center% error %/h5 结束转载于:https://www.cnblogs.com/zhuzhenwei918/p/6785259.html