简体   繁体   English

Express Node.js应用程序中的全局服务器会话

[英]Global server session in express node.js app

How should I gave access to the current session to the modules of my node.js app considering that I can only get it inside the request's function? 考虑到我只能在请求的函数中获取它,我应该如何授予当前会话访问我的node.js应用程序模块的权限?
It's a fairly complex but modular app and passing the session around seems a bit difficult, and I would have to reimplement a lot of things. 这是一个相当复杂但模块化的应用程序,传递会话似乎有些困难,我将不得不重新实现很多事情。
Ideally i would attach it to an object exported with module.exports and require it in other modules. 理想情况下,我会将其附加到使用module.exports导出的对象上,并在其他模块中要求它。 But I'm afraid that on concurrent requests it would get overwritten and I could end up with conflicts. 但是我担心,在并发请求上,它会被覆盖,最终导致冲突。

Have you tried res.locals ? 您尝试过res.locals吗? In the Official Docs, it says "Response local variables are scoped to the request, thus only available to the view(s) rendered during that request / response cycle, if any. This object is useful for exposing request-level information such as the request pathname, authenticated user, user settings etcetera. " 在正式文档中,它说:“响应局部变量的作用域为请求,因此仅在该请求/响应周期中呈现的视图(如果有)可用。此对象对于公开请求级信息(例如请求路径名,经过身份验证的用户,用户设置等。”

When your middleware/route callback is called, you can define res.locals.myProp = "some value" and access it from a view, using locals.myProp . 调用中间件/路由回调时,可以定义res.locals.myProp = "some value"并使用locals.myProp从视图访问它。

我通过使用express-domain-middleware解决了这一问题,该软件将来自express的传入请求和响应绑定到新

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM