NodeJS(Express.js):如何使Session全局化 [英] NodeJS (Express.js) : How to make the Session global

查看:117
本文介绍了NodeJS(Express.js):如何使Session全局化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道全局vars在javascript和整体编程中都是不好的做法,但是我想使我的用户会话在我的express.js应用程序中都可用,而不必将会话参数从我的控制器传递到我的所有设备上楷模.

I know that global vars are a bad practice in javascript and in programming overall, but i want to make my user session available throughout my express.js app, avoiding having to pass the session parameter all over, from my controllers to my models.

我怎样才能最好地做到这一点?

How can I best do this?

谢谢!

推荐答案

我最终像这样解决了这个问题:

I ended up solving this like so:

var appendLocalsToUseInViews = function(req, res, next)
{            
    //append request and session to use directly in views and avoid passing around needless stuff
    res.locals.session = req.session;
    next(null, req, res);
}

然后将其添加到中间件:

Then add it to the middleware:

app.use(appendLocalsToUseInViews);

这篇关于NodeJS(Express.js):如何使Session全局化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆