Friday 2 June 2017

Express Session not Working for Ajax Call

express-session config

{
    "key": "nsid",
    "secret": "some secret password",
    "cookie": {
        "path": "/",
        "httpOnly": false,
        "maxAge": null,
        "secure": false
    },
    "resave": true,
    "saveUninitialized": true,
    "proxy": null
}

routes.js

router.get('/temp', (req, res) => {
    const useCase = 'card';
    req.session = req.session || {};
    req.session.trackingInformation = {};
    req.session.trackingInformation.useCase = useCase;
    req.session.save();
    console.log(req.session);
    res.render('/temp');
});

router.get('/test', (req, res) => {
    console.log(Util.inspect(req.session));
    res.send({});
});

ajax call

fetch('/test').then((response) => {
    if (response.status >= 400) {
        console.log(response.status);
    }
    return response.json();
}).then((json) => {
    console.log(json);
    //do something
});

When I call the localhost:8000/temp and then call the /test as a fetch ajax call:

{
    "cookie": {
        "path": "/",
        "_expires": null,
        "originalMaxAge": null,
        "httpOnly": false,
        "secure": false
    },
    "_csrfSecret": "secret",
    "_shared": {
        "deviceInfo": {
        ...
        }
    }
}

The trackingInformation property clearly is not set. But if I call the same directly from my browser localhost:8000/test after first calling locahost:8000/temp, I have the trackingInformation set in the session.

{
    "cookie": {
        ...
    },
    "_csrfSecret": "secret",
    "_shared": {
        "deviceInfo": {
        ...
        }
    },
    "trackingInformation": {
        "useCase": "card"
    }
}



via ytibrewala

No comments:

Post a Comment