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

2019-06-20 04:53发布

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!

2条回答
我只想做你的唯一
2楼-- · 2019-06-20 05:43

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);
查看更多
太酷不给撩
3楼-- · 2019-06-20 05:47

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...

查看更多
登录 后发表回答