Store an instance in Express js session

不想你离开。 提交于 2020-01-05 10:26:09

问题


I'm using the expressjs session, and I have a instance need to store:

function a(){this.name="";}
var ins = new a();
req.session['user'] = ins;

and when I get res.session['user'] next time, the object is not instanceof a, and it cannot access any prototype methods in a, how can i store the ref of the object in session, looks the session will convert it to json object


回答1:


You can't store instances like that in JSON unless:

  • You provide your own custom serializer (implementing a toJSON() function in your class/object)
  • You also identify your serialized object and instantiate a new instance in the reviver function you pass to JSON.parse().



回答2:


One thing you can do is create an instances/session map which you can identify via the session.id, I blogged about this here:

https://tomblanchard.co.uk/storing-instances-in-express-sessions/



来源:https://stackoverflow.com/questions/23797119/store-an-instance-in-express-js-session

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