How to check session in Node.js Express?

后端 未结 4 1870
悲哀的现实
悲哀的现实 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:13

    From the source:

    How to use Express Session ?

    Before heading to actual code, i want to put few words about express-session module. to use this module, you must have to include express in your project. Like for all packages, we have to first include it.

    server.js
    var express = require('express');
    var session = require('express-session');
    var app = express();
    

    After this, we have to initialize the session and we can do this by using following.

    app.use(session({secret: 'ssshhhhh'}));
    

    Here ‘secret‘ is used for cookie handling etc but we have to put some secret for managing Session in Express.

    Now using ‘request‘ variable you can assign session to any variable. Just like we do in PHP using $_SESSION variable. for e.g

    var sess;
    app.get('/',function(req,res){
        sess=req.session;
        /*
        * Here we have assign the 'session' to 'sess'.
        * Now we can create any number of session variable we want.
        * in PHP we do as $_SESSION['var name'].
        * Here we do like this.
        */
        sess.email; // equivalent to $_SESSION['email'] in PHP.
        sess.username; // equivalent to $_SESSION['username'] in PHP.
    });
    

    After creating Session variables like sess.email , we can check whether this variable is set or not in other routers and can track the Session easily.

提交回复
热议问题