0

In my node app I use 4 routes to get data and asynchronously when the data is received, I'm setting the session. I use express.js and expression-session npm. But setting the session works time to time. (sporadically setting the data) . Sometimes all the data is no setting. Please help me out.

Important Code snippets

var session = require('express-session');
app.use(session({ secret: 'testQWERTY',cookie: { maxAge:  3600000 }}));

app.get('/route 1', function(req, res , next) {

var apiPortalURL = "testUrl";

        request({
            url: apiPortalURL,
            qs: {},
            json: req.body,
            method: 'GET',
            headers: {
                'Content-Type': 'application/json'
            }
        }, function(error, response, body){

            if(error) {
                console.log("error "+error);
                res.sendStatus(error);
            } else {
                req.session.data1 = response.body;
                res.status(response.statusCode);
                res.send(response.body);
            }
        });

});
app.get('/route 2', function(req, res , next) {
   //same as 1
   req.session.data2 = response.body;
});
app.get('/route 3', function(req, res , next) {
   //same as 1
   req.session.data3 = response.body;
});
app.get('/route 4', function(req, res , next) {
  //same as 1
   req.session.data4 = response.body;

});
Amila Iddamalgoda
  • 4,166
  • 11
  • 46
  • 85
  • You're setting data on the sesion *from* the response, before you've actually sent a response (or set the response body). There's absolutely no reason that should work. – ssube Feb 11 '16 at 16:26
  • that response in not the node js response but it is HTTP GET call response. and that response is not sending. node js response is 'res').Still cant figuring out what going here – Amila Iddamalgoda Feb 12 '16 at 03:36
  • req.session.data1 = response.body; Here response.body is populated with data (from the http get) . So dont get confused with that. – Amila Iddamalgoda Feb 12 '16 at 04:17
  • this code is working sporadically. sometimes all 4 data is set in the session. some time only data2 is set. some times both data2 and data3 is set. :( – Amila Iddamalgoda Feb 12 '16 at 04:19
  • How are routes 2-4 supposed to be accessing the response variable? They don't have closure and you aren't declaring it in your example. – ssube Feb 12 '16 at 04:22
  • they are not declare in the example . they are same as route 1. – Amila Iddamalgoda Feb 12 '16 at 06:51

0 Answers0