尝试为Express 3.0应用程序编写一些辅助方法。这是一个迎接用户的示例:

  app.locals.greet = function(req,res) {
    return "hey there " + req.user.name;
  }


但是,reqres在该函数内不可用。我该如何编写可以在我的Jade模板中使用的助手?我做错了吗?

最佳答案

看看我的配置app.js文件!应该会为您工作,因为变量将在该上下文中可用。

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);
});

关于javascript - 在app.locals内部访问req和res,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13886897/

10-11 09:31