node.js - 如何在Express.js 4.* 的大量模板中访问req.session?
阿神
阿神 2017-04-17 13:01:32
[Node.js讨论组]

架构是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 ?

阿神
阿神

闭关修行中......

全部回复(1)
高洛峰

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

解决方案参考: 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了。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号