Session: Express session object getting removed

Created on 24 Mar 2018  路  4Comments  路  Source: expressjs/session

https://stackoverflow.com/questions/49467757/how-to-track-req-session-variable-with-node-inspectorapp.js

I am facing a perplexing issue I am setting a object to req.session and gets set after I exit app.get() method the object magically gets removed from the cart.
I have no way of finding its only happening to this as you can see in cart.js I am adding the flash mess as well which gets through it except for cart object added before it

var express = require('express');
var path  = require('path');
var app = express();

var config = require('./config/database');



var port='3000';
app.listen(port,function(){
    console.log('server listening on port'+port);
});



var mongoose = require('mongoose');
mongoose.connect(config.database);
var db = mongoose.connection;

db.on('error', console.error.bind(console,'connection error'));

db.on('open',function(){
    console.log('connected to the database');
});




var session = require('express-session');
var validator = require('express-validator');
var messages = require('express-messages');
var bodyparser = require('body-parser');
var fileupload = require('express-fileupload');

var mkdirp  = require('mkdirp');

var  pageModel = require('./models/pages.js');
var catModel = require('./models/category.js');
console.log(mkdirp);

var fs = require('fs-extra');
var resizeimage = require('resize-img');
app.locals.hasError = null;

app.set('views',path.join(__dirname,'views'));
app.set('view engine','ejs');


app.use('/static', express.static(path.join(__dirname, 'public')))


app.use(fileupload());


app.use(bodyparser.urlencoded({extended:true}));
app.use(bodyparser.json());

app.use(session({

  secret: 'keyboard cat',
  resave: true,
  saveUninitialized: true
  //cookie: { secure: true }
}));

app.use(validator({

    errorFormatter: function(param ,msg , value)
    {
        var nameSpace = param.split('.')
        , root = nameSpace.shift(),
        formParam = root;

        while(nameSpace.length)
        {
            formParam+='['+nameSpace.shift()+']' ;
        }
        return {

               param : formParam,
               msg   : msg,
               value : value
        };

    },

}));



app.all('*', function (req, res, next) {
  console.log('req.session');
  console.log(req.session);
  console.log('req.sessionID'+req.sessionID);
  next(); // pass control to the next handler
});

app.use(require('connect-flash')());
app.use(function (req, res, next) {
  res.locals.messages = require('express-messages')(req, res);

 // console.log("New cart variable");
  //console.log(req.session.cart);
  //console.log(req.locals);
  //console.log(req.app.locals.cart);

  if(req.session.cart!=="undefined"){
    app.locals.cart=[];
    app.locals.cart = req.session.cart ; 
  }
  next();
});
pageModel.find({}).sort({sorting:-1}).exec(function(err,pages){

        app.locals.pages=pages;

});
catModel.find({},function(err,cat){

        app.locals.cat=cat;

});

require('./routes/pages.js')(app);
require('./routes/category.js')(app);
require('./routes/product.js')(app);
require('./routes/cart.js')(app);

cart.js
````
var productModel =require('../models/products.js');
var categoryModel =require('../models/category.js');

module.exports=(app)=>{

app.get('/add-to-cart/:id',function(req,res){

    //console.log("Cart get started");
            var quantity,subtotal = 0;
            productModel.findOne({'_id':req.params.id},function(err,p){
                    //console.log("product consoled"+p);
                    if(err){
                        return console.log(err);
                    }
        if( typeof req.session.cart == "undefined"){

            //console.log("Session undefined check");

            quantity=1;
            req.session.cart = [];

            req.session.cart.push({
                title : p.title,
                price : p.price,
                image : '/static/Product_images/'+p._id+'/'+p.image,
                quantity:quantity,
                subtotal : p.price

            });

             console.log("#### The request var session inside cart function start");

             console.log("#### The request var session var end");

            req.app.locals.cart=[];
            req.app.locals.cart.push({
                title : p.title,
                price : p.price,
                image : '/static/Product_images/'+p._id+'/'+p.image,
                quantity:quantity,
                subtotal : p.price

            });
            //console.log(req.app.locals);
            //console.log("Session set ");

            //console.log(req.session.cart);

    console.log("Cart got set");
    console.log(req.session);

        }else{

/*
var product = req.session.cart;
var productFound = false;
product.forEach(function(prod){

                        if(prod.title==p.title){
                            prod.quantity+=1;
                            prod.subtotal=prod.quantity*prod.price;
                            productFound=true;

                        }


                });

                req.session.cart=product;
                if(!productFound){
                        quantity=1;
                        req.session.cart.push({
                        title : p.title,
                        price : p.price,
                        image : '/static/Product_images/'+p._id+'/'+p.image,
                        quantity:quantity,
                        subtotal : p.price

                    });
                }*/
        }

    });     //console.log("req.session.cart");
            //console.log(req.session.cart);

            req.flash('success','product added to cart');
            res.redirect('back');
});

}
```

awaiting more info

Most helpful comment

https://github.com/sachindivakar2/fcart
node version 8.9.4
npm version 5.6.0

this is repository full repository is added

To replicate the issue
go to
http://localhost:3000/categories/all-products
or any other product categories after adding some products and categories from here
http://localhost:3000/admin/products
http://localhost:3000/admin/categories

and after that if click on any of product in the product page http://localhost:3000/categories/all-products and then add to cart from the product page when add to cart happens the
https://stackoverflow.com/questions/49467757/how-to-track-req-session-variable-with-node-inspector-to-understand-how-a-sessio

the req.session.cart is added as a an array

its consoled successfully
then once res.back is executed and the
call is interecpted using request interceptor
here the added cart object inside session disappears

app.all('*', function (req, res, next) {
    console.log(req.session)

  next(); // pass control to the next handler
});

All 4 comments

Hi @sachindivakar2 sorry you're having trouble! I'm happy to take a look and debug through it to see what the bug is in this module. I see you've provide some code already, but there is a lot of the code not included, it seems. Can you help us get a running app so we can see the issue happening?

  1. Version of Node.js
  2. Version of this module and al other necessary modules
  3. Complete code we can run (this code is referencing files not provided here). It doesn't need to be your actual, real code, just code that is self-contained enough to work and demonstrate the issue
  4. Instructions for how to get the code setup and running
  5. Instructions for the step-by-step to see the issue happening

Thank you! Looking forward to dig in and track down the express-session bug.

https://github.com/sachindivakar2/fcart
node version 8.9.4
npm version 5.6.0

this is repository full repository is added

To replicate the issue
go to
http://localhost:3000/categories/all-products
or any other product categories after adding some products and categories from here
http://localhost:3000/admin/products
http://localhost:3000/admin/categories

and after that if click on any of product in the product page http://localhost:3000/categories/all-products and then add to cart from the product page when add to cart happens the
https://stackoverflow.com/questions/49467757/how-to-track-req-session-variable-with-node-inspector-to-understand-how-a-sessio

the req.session.cart is added as a an array

its consoled successfully
then once res.back is executed and the
call is interecpted using request interceptor
here the added cart object inside session disappears

app.all('*', function (req, res, next) {
    console.log(req.session)

  next(); // pass control to the next handler
});

Hi @sachindivakar2 I apologize that this issue has gotten lost in time. I'm going through all the issues in this repo and trying to clean them up. I tried to follow the given steps, and I'm not able to get it going. Here is what I did:

(1) git clone [email protected]:sachindivakar2/fcart.git
(2) In fcart, I wasn't sure how to start the app. npm start did nothing, and since there is a app.js file, I ran node app.js with Node.js 8.9.4 and the following was printed, but it did stay running:

$ node app.js 
{ [Function: mkdirP]
  mkdirP: [Circular],
  mkdirp: [Circular],
  sync: [Function: sync] }
server listening on port3000
connection error { MongoNetworkError: failed to connect to server [127.0.0.1:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]
    at Pool.<anonymous> (/node_modules/mongodb-core/lib/topologies/server.js:503:11)
    at emitOne (events.js:116:13)
    at Pool.emit (events.js:211:7)
    at Connection.<anonymous> (node_modules/mongodb-core/lib/connection/pool.js:326:12)
    at Object.onceWrapper (events.js:317:30)
    at emitTwo (events.js:126:13)
    at Connection.emit (events.js:214:7)
    at Socket.<anonymous> (node_modules/mongodb-core/lib/connection/connection.js:245:50)
    at Object.onceWrapper (events.js:315:30)
    at emitOne (events.js:116:13)
    at Socket.emit (events.js:211:7)
    at emitErrorNT (internal/streams/destroy.js:66:8)
    at _combinedTickCallback (internal/process/next_tick.js:139:11)
    at process._tickCallback (internal/process/next_tick.js:181:9)
  name: 'MongoNetworkError',
  message: 'failed to connect to server [127.0.0.1:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]' }
(node:83073) UnhandledPromiseRejectionWarning: MongoNetworkError: failed to connect to server [127.0.0.1:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]
    at Pool.<anonymous> (node_modules/mongodb-core/lib/topologies/server.js:503:11)
    at emitOne (events.js:116:13)
    at Pool.emit (events.js:211:7)
    at Connection.<anonymous> (node_modules/mongodb-core/lib/connection/pool.js:326:12)
    at Object.onceWrapper (events.js:317:30)
    at emitTwo (events.js:126:13)
    at Connection.emit (events.js:214:7)
    at Socket.<anonymous> (node_modules/mongodb-core/lib/connection/connection.js:245:50)
    at Object.onceWrapper (events.js:315:30)
    at emitOne (events.js:116:13)
    at Socket.emit (events.js:211:7)
    at emitErrorNT (internal/streams/destroy.js:66:8)
    at _combinedTickCallback (internal/process/next_tick.js:139:11)
    at process._tickCallback (internal/process/next_tick.js:181:9)
(node:83073) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:83073) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

I tried to go to http://localhost:3000/categories/all-products in Chrome and it just didn't load anything and eventually timed out.

I'm going to close this issue for now since I wasn't able to get the app running and never got any further information to do so.

Was this page helpful?
0 / 5 - 0 ratings