是分离出去变中间件了,还是其他。找了一个早上,资源太匮乏了 app.dynamicHelpers() (use middleware + res.locals) 不明呀!!!! app.helpers() (use app.locals) 以验证
给个例子最好
2.x:
app.helpers({
config: config,
title: config.title
});
app.dynamicHelpers({
//防止csrf攻击
csrf: function(req,res) {
return req.session ? req.session._csrf : '';
},
req: function(req,res) {
return req;
},
userInfo: function(req,res){
return req.session.user;
}
});
3.x
//app.helpers()
app.locals({
config: config,
title: config.title
});
//app.dynamicHelpers
app.use(function(req, res, next){
res.locals.title = config['title']
res.locals.csrf = req.session ? req.session._csrf : '';
res.locals.req = req;
res.locals.session = req.session;
next();
});
app.use(app.router);
res.locals.csrf = req.session ? req.session._csrf : '’;确定可以这样写?
res.locals.success=req.flash(“success”).lenght?req.flash(“success”):null; 无效
说实话还是不能理解为什么要把dynamicHelpers给删掉,哪怕有别的方式可以实现,也可以保留来达到结构清晰。
做了好多年js,最近在看node,还是觉得学习曲线有点陡峭。太小众了,资料少的可怜~~
app.use(function(req, res, next){ //res.locals.title = config['title'] //res.locals.csrf = req.session ? req.session._csrf : ''; res.locals.req = req; res.locals.session = req.session; res.locals.error = req.error; res.locals.success = req.success; res.locals.docs = req.docs; next(); });//locals
我已经定义了success,为什么页面所success未定义呢?
`ReferenceError: c:\node\project\microblog\views\layout.ejs:42
40|
41| <div id="container" class="container">
42| <% if (success) { %> 43|
44| <%= success %> 45|
success is not defined`
书本的例子
app.dynamicHelpers({ user: function (request, response) { return request.session.user; }, error: function (request, response) { var err = request.flash(‘error’); if (err.length) return err; else return null; }, success: function (request, response) { var succ = request.flash(‘success’); if (succ.length) return succ; else return null; } }); 现在也不行了,3已经益处了这个API,搜索了一下,好像说用"everyauth" 但是我不知道要怎么使用,哎。。。express3之后,好多模块都改变了,苦逼啊。
现在版本的req.flash取了一次值之后就无效了。。所以req.flash(“success”).lengh?req.flash(“success”):null; 前面那个值是1,后面req.flash(“success”)已经变成null了。。。
我写的代码是这样的: app.locals({ inspect:function(obj){ return util.inspect(obj,true); } });
app.use(function(req,res,next){ res.locals.headers = req.headers; next(); }); app.get('/helper’,function(req,res){ res.render('helper’,{title:’Helpers’}); }); helper.ejs代码如下:<%= inspect(headers)%> 问什么访问总是报headers is not defined求指点这是怎么回事啊?