简体   繁体   中英

Node JS Session not persisting

I'm having a bit of a nightmare with setting up user sessions in NodeJS. I have googled the life out of it and read a whole host of articles on here but none of the solutions work for me.

My setup:

app.use(cookieParser());
    app.use(session({
        pool: true,
        key: 'cgtracker.cookie',
        resave: false,
        saveUninitialized: false,
        secret: '1234567890QWERTY',
        cookie: {maxAge: 100000},
        store: new MySQLStore(options),
    }));

I am using MySQLStore ('express-mysql-session'). This is linked to my Db and is working as expected.Running this ->

router.post('/Login', function (req, res) {
        logger.log("info", "Attempting Login for user: " + req.body.Username);
        req.session.username = req.body.Username;
        res.send('Created session for: ' + req.body.Username);

Creates an entry in my session table for a session with an expiry.

| 2gbIWNuFVcE3GmjrFMEctdZlvBMufqiN | 1457713316 | {"cookie":{"originalMaxAge":100000,"expires":"2016-03-11T16:21:55.580Z","httpOnly":t                                                      rue,"path":"/"},"username":"chris.rayner"} 

My problem is that I can't retrieve any session in any other function. A simple test here:

router.get('/', function (req, res) {
        logger.log("info", "Current Session: " + JSON.stringify(req.session));
}

I receive:

Current Session: {\"cookie\":{\"originalMaxAge\":100000,\"expires\":\"2016-03-11T16:24:15.212Z\",\"httpOnly\":true,\"path\":\"/\"}}","timestamp":"2016-03-11T16:22:35.212Z"}`

Where is my Session data gone?!

I feel like I'm missing something obvious, but I have tried so many variations from research I'm becoming a little lost.

My browser cookie is constructed correctly, though the value doesn't seem to correlate to any of the SessionID's stored in the session table.

Any help/ideas/suggestions would be very much appreciated!

Chris

Found the solution!

Chrome (and maybe firefox, but not tested) by default blocks cookies in POST requests when posting to a "unknown" domain. Some security feature in clientside CORS...

To fix this server side: -Update Cors with an authorized origin(s) for the browser to check against.

app.use(cors({ origin: config.origin, *(I am using an array for multiple allows origins)* credentials: true }));

To fix this Client Side: Add this to the options in the POST header for a function.

xhrFields: { withCredentials: true }

OR

Add this to the Model Constructor for a Class.

$.ajaxPrefilter( function( options, originalOptions, jqXHR ) { options.xhrFields = { withCredentials: true }; });

After this, Cookies made in POST requests successfully "Stick" to the browser and Session functionality is a go!

What a pain! Hope this solution helps somebody else save some time on their project!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM