req.session is undefined using express-session

前端 未结 4 1963
梦毁少年i
梦毁少年i 2020-12-30 04:09

I am just starting to learn how to use cookies with node and express and I would like some help with getting this to work. I tried to follow the expressjs/session tutorial o

相关标签:
4条回答
  • 2020-12-30 04:55

    This problem occurred with me while trying to maintain req.session object in my app. I was setting req.session.user in a login route, but was not able to get the same outside that route.

    console.log(req.session) 
    // undefined
    

    Since there was no use of cookie in my app, I removed it.

    Before removing cookie variable:

    app.use(
    session({
        resave: false,
        saveUninitialized: true,
        secret: "anyrandomstring",
        cookie: { secure: true},
      })
    );
    

    After removing cookie variable:

    app.use(
    session({
        resave: false,
        saveUninitialized: true,
        secret: "anyrandomstring",
      })
    );
    

    This resolved my issue. And now I was able to access req.session from anywhere in the app.

    console.log(req.session)
    /* Session{
         ......
         ......
        }
    */
    

    Note: This issue might also occurs if you have initialized app.use(session({...})) at bottom of the file. Try to bring it to the top.

    Why this happens: Click here

    0 讨论(0)
  • 2020-12-30 04:57

    You will also see req.session === undefined if your Redis connection is invalid or missing!

    I don't see anywhere in your code where connection info is being passed when configuring the session.

    0 讨论(0)
  • 2020-12-30 05:03

    Once you mount a router onto an Express app, any subsequently declared middleware on that app won't get called for any requests that target the router.

    So if you have this:

    app.use(router)
    app.use(session(...));
    

    The session middleware won't get called for any requests that get handled by router (even if you declare the routes that the router should handle at some later point). For that, you need to change the order:

    app.use(session(...));
    app.use(router);
    

    An additional issue is that you're exporting router, which should probably be app (which is the instance that "holds" all the middleware, routers, etc):

    module.exports = app;
    
    0 讨论(0)
  • 2020-12-30 05:03

    To get session data

    first , You have to initialize express-session with

    app.use(session({ resave: true ,secret: '123456' , saveUninitialized: true}));
    

    then When you want to put something in the session

    req.session.firstName = 'Aniruddha';
    req.session.lastName = 'Chakraborty';
    

    Then you can check without errors

    console.log('req.session: '+req.session.firstName);
    

    Note: This is express-sessions work!

    0 讨论(0)
提交回复
热议问题