在app.locals内部访问req和res [英] Access req and res inside of app.locals
本文介绍了在app.locals内部访问req和res的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
尝试为Express 3.0应用程序编写一些辅助方法。这是一个向用户打招呼的示例:
Trying to write some helper methods for an express 3.0 app. Here is an example to greet the user:
app.locals.greet = function(req,res) {
return "hey there " + req.user.name;
}
但是,要求
和 res
在该函数中不可用。我该如何编写可以在我的Jade模板中使用的助手?我做错了吗?
However, req
and res
aren't available inside that function. How would I go about writing helpers that I can use inside my jade templates? Am I doing this wrong?
推荐答案
看看我的配置 app.js
文件!应该对您有用,因为变量将在该上下文中可用。
Have a look at my config app.js
file! that should work to you as the variables will e available at that context.
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(connect.compress());
app.use(express.static(__dirname + "/public", { maxAge: 6000000 }));
app.use(express.favicon(__dirname + "/public/img/favicon.ico", { maxAge: 6000000 }));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.session({
secret: config.sessionSecret,
maxAge: new Date(Date.now() + (1000 * 60 * 15)),
store: new MongoStore({ url: config.database.connectionString })
}));
app.use(function(req, res, next){
console.log("\n~~~~~~~~~~~~~~~~~~~~~~~{ REQUEST }~~~~~~~~~~~~~~~~~~~~~~~".cyan);
res.locals.config = config;
res.locals.session = req.session;
res.locals.utils = viewUtils;
res.locals.greet = function(){
//req and res are available here!
return "hey there " + req.user.name;
};
next();
});
app.use(app.router);
});
这篇关于在app.locals内部访问req和res的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文