How to check session in Node.js Express?

后端 未结 4 1884
悲哀的现实
悲哀的现实 2021-02-15 04:31

I try to check if session in Express 4 is exist:

if(req.session.user == undefined) {}

It gives me error:

 Cannot read property          


        
4条回答
  •  悲哀的现实
    2021-02-15 05:23

    Firstly it depends on the library you are using, maybe some libraries have utilities for that, I assume you're using express-session.

    This is just Okay:

    if(req.session.user){}
    

    They are useless:

    if(typeof req.session.user !== "undefined"){}
    
    if(typeof req.session.user !== "undefined" || req.session.user === true){}
    

    The reason: req.session is an object, just like normal objects:

    var obj = { name : "adam" }
    

    If you try to get obj.age which it doesn't exist and defined, the getter function of the object, firstly check if it exists or not, if it's not, it wouldn't produce a fatal error and instead it assigns that property to undefined value.

    That's cool, so obj.age get's undefined ( JS has undefined as a value type), moreover undefined is a falsy value (when you coerce it to boolean it becomes false, so it's falsy), which means you can simply check it in conditional statements like this: if(obj.age){}

提交回复
热议问题