NodeJS (Express.js) : How to make the Session global

淺唱寂寞╮ 提交于 2019-12-13 13:02:35

问题


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?

Thanks!


回答1:


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



回答2:


if you really want to do this, add the request or session to the global-object of node though i would also not recommend this...



来源:https://stackoverflow.com/questions/21164042/nodejs-express-js-how-to-make-the-session-global

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!