求教express3.0中locals代替dynamicHelpers()的用法 route里修改res.locals.xx变量:书上APP.JS代码
app.dynamicHelpers({
user: function(req, res) {
return req.session.user;
},
error: function(req, res) {
var err = req.flash('error');
if (err.length)
return err;
else
return null;
},
success: function(req, res) {
var succ = req.flash('success');
if (succ.length)
return succ;
else
return null;
},
});
router里代码:`
exports.doReg = function(req, res) {
//检查密码
if (req.body['password-repeat'] != req.body['password']) {
req.flash('error', '两次输入的密码不一致');
return res.redirect('/reg');
}
//生成md5的密码
var md5 = crypto.createHash('md5');
var password = md5.update(req.body.password).digest('base64');
var newUser = new User({
name: req.body.username,
password: password,
});
//检查用户名是否已经存在
User.get(newUser.name, function(err, user) {
if (user)
err = 'Username already exists.';
if (err) {
req.flash('error', err);
console.log(res.locals.error);
return res.redirect('/reg');
}
//如果不存在則新增用戶
newUser.save(function(err) {
if (err) {
req.flash('error', err);
return res.redirect('/reg');
}
req.session.user = newUser;
req.flash('success', '注册成功');
res.redirect('/');
});
});
};`
由于expresss3.0中已经去除dynamicHelpers()方法 现想用res.locals方法代替原来代码 现APP。JS替换代码
app.use(function(req,res,next){
res.locals.user=req.session.user;
res.locals.error=req.flash('error').length?req.flash('error'):null;
res.locals.success=req.flash('success').length?req.flash('success'):null;
next();
});
app.get('/', routes.index);
app.get('/u/:user', routes.user);
app.post('/post', routes.post);
app.get('/reg', routes.reg);
app.post('/reg', routes.doReg);
app.get('/login', routes.login);
app.post('/login', routes.doLogin);
app.get('/logout', routes.logout);
router里值无法传递给res.locals.xxx 因在论坛只找到原因是因为先执行的lcoals后执行route 所以无法再传递值res.locals.xxx ,给实在找不到解决方法,特请教各位高手指点一下如果解决传递值方法
把
app.use(function(req,res,next){
res.locals.user=req.session.user;
....
next();
});
放在
app.use(app.router);
之前试试
我的笨方法里在每个路由都塞值。如: exports.login=function(req,res){ res.render(‘login’,{ user:req.session.user, success:req.flash(‘success’), error:req.flash(‘error’),
}); } 各位有好方法也晒一下吧。
我也是采用的这个方法、、、
用app.locals呢?不知道和res.locals的区别在那,在express的文档里看到的
app.locals Application local variables are provided to all templates rendered within the application. This is useful for providing helper functions to templates, as well as app-level data.
req.flash()方法在Express3.0中已经被删掉,要怎么用?
npm install connect-flash
安装这个模块
在 app.configure里加入 app.use(flash())
应该是顺序问题,我的app.js,如下 code ```app.configure(function(){ app.set(‘port’, process.env.port || 3000); app.set(‘views’, __dirname + ‘/views’); app.set(‘view engine’, ‘ejs’); app.engine(‘ejs’, require(‘ejs’).__express); //加载子模板文件 app.use(partials()); app.use(flash()); app.use(express.favicon()); app.use(express.bodyParser({ upload_dir: config.upload_dir })); app.use(express.methodOverride()); app.use(express.cookieParser(config.cookie_secret)); app.use(express.session()); app.use(app.router); app.use(express.static(__dirname+’/public’)); });
app.configure(‘development’, function(){ app.use(express.errorHandler({ dumpExceptions: true, showStack: true})); }); app.configure(‘production’, function(){ app.use(express.errorHandler()); }); app.use(function(req,res,next){ res.locals.user = req.session ? req.session.user:’’; res.locals.keyword = req.session ? req.session.keyword:’’; }); routes(app); //listen http.createServer(app).listen(3000, function(){ console.log(“express server listening on 3000” ; });```
@zs1621 可以了 谢了
在app.js 添加
app.use(function (req, res, next) {
res.locals.error = req.flash('error');
res.locals.success = req.flash('success');
res.locals.user = req.session.user;
next();
});
就可以实现全局了。
前端模版这样做判断
<% if (success && success.length ) { %>
<div class="alert alert-success">
<a class="close" data-dismiss="alert" href="#">×</a>
<<strong><%= success %></strong>
</div>
<% } %>
@gyrate 你的方法靠谱
@duyinghua 重定向最后怎么解决啊
@gyrate Good!!!
require(“connect_flash”)
app.js: app.use(function(req, res, next){ res.locals.user = req.session.user; res.locals.error = ‘’; res.locals.success = ‘’; next(); });
layout.ejs: <% if (success!=’’) { %> <div class=“alert alert-success”><%= success %></div> <% } %> <% if (error!=’’) { %> <div class=“alert alert-error”><%= error %></div> <% } %>
@duyinghua 你没赋值 当然是空的
flash 闪出 的意思,PHP里面很多框架都有这个功能,CI TP Yii框架里面都有的
好案例
楼主给的代码是有错误的。 app.use(function(req,res,next){
res.locals.user=req.session.user;
res.locals.error=req.flash('error').length?req.flash('error'):null; // 调用req.flash('error') 返回值,随后立即情况error属性值。在后面的 第二次调用,就会返回一个空集合,所以模版渲染的时候就得不到数据。正确做法应该先用一个过渡变量拷贝一份
res.locals.success=req.flash('success').length?req.flash('success'):null;
next();
});