如何在Express.js 4.* 的大量模板中访问req.session?


架构是Node.js 4.* + Express 4.13, 使用的模板是 Nunjucks。我知道可以通过在每个具体的routes中通过将 req.session 传递进 res.render 函数,可以使得模板访问 session:


 router.get('/', function(req, res, next) {
    res.render('index', {
        session: req.session
    });
});

但是这样的量太大了,重复代码太多。每个 render 方法多要这样传递一次。请问除此之外,如何在所有的模板中可以访问到 req.session ?

Express node.js

狂気D優曇華院 8 years, 7 months ago

擦,又是自问自答了。。。

解决方案参考: ExpressJS exposing variables and session to Jade templates

然后顺着这个文章,看Express.js 4.* 的API文档,如下介绍:

res.locals

An object that contains response local variables scoped to the request, and therefore available only to the view(s) rendered during that request / response cycle (if any). Otherwise, this property is identical to app.locals.

This property is useful for exposing request-level information such as the request path name, authenticated user, user settings, and so on.

示例代码:


 app.use(function(req, res, next){
  res.locals.user = req.user;
  res.locals.authenticated = ! req.user.anonymous;
  next();
});

对于我具体提问的情形,在所有的路由代码之前,加入该代码:


 app.use(function(req, res, next){
    res.locals.session = req.session;
    next();
});

然后就可以在模板里面直接访问 session 了。

绝对领域我最爱 answered 8 years, 7 months ago

Your Answer