问题
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