connect-flash 的使用分享
发布于 8 年前 作者 youarenode 6471 次浏览 来自 分享

最近在express框架处理页面消息提示使用了 connect-flash 感觉不错 因为 connect-flash 是需要存储在 session 模块,需要安装 express-session

安装:

	npm install express-session
	npm install connect-flash

配置app.js:

	var flash = require('connect-flash');
	var session = require('express-session');
	
	app.use(session({
		secret: hibaby,  
 		key: fuckbaby, 
  		cookie: {maxAge: 60000},
  		resave: false,
  		saveUninitialized: true,
	}));
	app.use(flash());

	// 设置 error info两个变量信息
	app.use(function (req, res, next) {
  		res.locals.errors = req.flash('error');
  		res.locals.infos = req.flash('info');
  		next();
	});

处理使用:

	userPost : function(req, res, next){
		var data = req.body;
		var addSql = "INSERT INTO project(id, type, project, version, name, url, person, pm, ui) VALUES(0, "+'\''+data.type+'\''+", "+'\''+data. project+'\''+", "+'\''+data.version+'\''+", "+'\''+data.name+'\''+", "+'\''+data.url+'\''+", "+'\''+data.person+'\''+", "+'\''+data.pm+'\''+", "+'\''+data.ui+'\''+")";
			if(data.type == '' || data.project == '' || data.version == '' || data.name == '' || data.url == '' || data.person == '' || data.pm == '' || data.ui === ''){
				req.flash('error','信息填写错误!');
				return res.redirect('/guidepc?edit=fed');
			}else{			
				query(addSql, function (err, result, fields) {
					if(err){
						console.log('[INSERT ERROR] - ', err.message);
						req.flash('error','database error!');
						return res.redirect('/guide');
					}else{
						req.flash('info','执行成功!');
						return res.redirect('/guide');
					}
				});
			}
	}

handlebars :

	<div id="message"> {{errors}} {{infos}}</div>

测试: QQ截图20161110111147.png

路由位置很关键!!

1 回复

怎么控制flash的显示时间?

回到顶部