3

I am having an issue accessing a saved req.session object. It seems that it is accessing a new req.session with a new api call.

This is my server.js

const logger     = require('morgan');
const express    = require('express');
const bodyParser = require('body-parser');
const session    = require('express-session');
const cookieParser = require('cookie-parser');
const path       = require('path');
const apiRoute   = require('./routes/api');
const webpack    = require('webpack');
const config     = require('./webpack.config');

const app        = express();
const compiler   = webpack(config);
const port       = process.env.PORT || 3000



app.use(express.static(path.join(__dirname, 'dist')));
app.use(logger('dev'))


app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.use(cookieParser("sdd", {signed: true}))
app.use(session({
 secret: 'superSecretCodez',
 resave:true,
 saveUninitialized:true,
 cookie: { maxAge: 60000 }
}))

app.use('/api', apiRoute)

app.listen(port, () => {
 console.log('Server is listening on port', port);
})

My initial api request is a get request,

router.get('/start', createGame, (req, res) => {
  res.status(200).json({response: res.game});
})

function createGame(req, res, next){
  if(req.originalUrl === '/api/start'){
    const game = new BattleShip();
    console.log(game)
    res.game = game
    req.session.game = res.game
    req.session.save(function(err){
      console.log('session saved');
      console.log("Session Before Redirect: ", req.session);
    })
  }
  next();
}

and in viewing the req.session object there, req.session.game is in the req.session.

session saved
Session Before Redirect:  Session {
  cookie: 
   { path: '/',
     _expires: 2016-10-11T03:18:40.520Z,
     originalMaxAge: 60000,
     httpOnly: true },
  game: 
   BattleShip {
     cpuBoard: [ [Object], [Object], [Object], [Object], [Object] ],
     playerBoard: [ [Object], [Object], [Object], [Object], [Object] ],
     cpuCoordinates: [],
     playerCoordinates: [],
     playerSelections: [],
     cpuSelections: [] } }
BattleShip {
  cpuBoard: 
   [ [ 'A0', 'A1', 'A2', 'A3', 'A4' ],
     [ 'B0', 'B1', 'B2', 'B3', 'B4' ],
     [ 'C0', 'C1', 'C2', 'C3', 'C4' ],
     [ 'D0', 'D1', 'D2', 'D3', 'D4' ],
     [ 'E0', 'E1', 'E2', 'E3', 'E4' ] ],
  playerBoard: 
   [ [ 'A0', 'A1', 'A2', 'A3', 'A4' ],
     [ 'B0', 'B1', 'B2', 'B3', 'B4' ],
     [ 'C0', 'C1', 'C2', 'C3', 'C4' ],
     [ 'D0', 'D1', 'D2', 'D3', 'D4' ],
     [ 'E0', 'E1', 'E2', 'E3', 'E4' ] ],
  cpuCoordinates: [],
  playerCoordinates: [],
  playerSelections: [],
  cpuSelections: [] }

The issue arises later, when I'm doing a post request and trying to access the same session to update it.

router.post('/setShips', setPlayerShips, createCpuCoordinates, (req, res) => {
  res.status(200).json({response: res.cpuCoordinates})
  // set up coordinates, players div should be updated with divs
})

function setPlayerShips(req, res, next){
  console.log(req)
  console.log(req.session)
  console.log(req.session.game)
  if(req.originalUrl=== '/api/setShips'){
      res.playerCoordinates = req.body
      req.session.game.BattleShip.playerCoordinates = res.playerCoordinates
  }
  next();
}

It seems to be accessing an entirely different cookie, which does not have req.session.game. however, there are session objects within the req object, in the session store.

 sessionStore: 
   MemoryStore {
     domain: null,
     _events: 
      { disconnect: [Function: ondisconnect],
        connect: [Function: onconnect] },
     _eventsCount: 2,
     _maxListeners: undefined,
     sessions: 
      { i2R3lJZxEneAheOciHO9QX7_dCjOyFPG: '{"cookie":{"originalMaxAge":60000,"expires":"2016-10-11T03:18:40.487Z","httpOnly":true,"path":"/"},"game":{"cpuBoard":[["A0","A1","A2","A3","A4"],["B0","B1","B2","B3","B4"],["C0","C1","C2","C3","C4"],["D0","D1","D2","D3","D4"],["E0","E1","E2","E3","E4"]],"playerBoard":[["A0","A1","A2","A3","A4"],["B0","B1","B2","B3","B4"],["C0","C1","C2","C3","C4"],["D0","D1","D2","D3","D4"],["E0","E1","E2","E3","E4"]],"cpuCoordinates":[],"playerCoordinates":[],"playerSelections":[],"cpuSelections":[]}}',
        'MLxoJNCuxn29GO-cCZyisjUwdLGhHf6l': '{"cookie":{"originalMaxAge":60000,"expires":"2016-10-11T03:18:41.083Z","httpOnly":true,"path":"/"},"game":{"cpuBoard":[["A0","A1","A2","A3","A4"],["B0","B1","B2","B3","B4"],["C0","C1","C2","C3","C4"],["D0","D1","D2","D3","D4"],["E0","E1","E2","E3","E4"]],"playerBoard":[["A0","A1","A2","A3","A4"],["B0","B1","B2","B3","B4"],["C0","C1","C2","C3","C4"],["D0","D1","D2","D3","D4"],["E0","E1","E2","E3","E4"]],"cpuCoordinates":[],"playerCoordinates":[],"playerSelections":[],"cpuSelections":[]}}' },
     generate: [Function] },
  sessionID: 'aHfVNblu917HOdlRR1kbIqb9JsUFfM-6',
  session: 
   Session {
     cookie: 
      { path: '/',
        _expires: 2016-10-11T03:18:48.163Z,
        originalMaxAge: 60000,
        httpOnly: true } },
  route: 
   Route {
     path: '/setShips',
     stack: [ [Object], [Object], [Object] ],
     methods: { post: true } } }
Session {
  cookie: 
   { path: '/',
     _expires: 2016-10-11T03:18:48.163Z,
     originalMaxAge: 60000,
     httpOnly: true } }
undefined
TypeError: Cannot read property 'BattleShip' of undefined
    at setPlayerShips (/Users/dfrank/code/projects/battleShip/api/game_controls.js:34:23)
    at Layer.handle [as handle_request] (/Users/dfrank/code/projects/battleShip/node_modules/express/lib/router/layer.js:95:5)
    at next (/Users/dfrank/code/projects/battleShip/node_modules/express/lib/router/route.js:131:13)
    at Route.dispatch (/Users/dfrank/code/projects/battleShip/node_modules/express/lib/router/route.js:112:3)
    at Layer.handle [as handle_request] (/Users/dfrank/code/projects/battleShip/node_modules/express/lib/router/layer.js:95:5)
    at /Users/dfrank/code/projects/battleShip/node_modules/express/lib/router/index.js:277:22
    at Function.process_params (/Users/dfrank/code/projects/battleShip/node_modules/express/lib/router/index.js:330:12)
    at next (/Users/dfrank/code/projects/battleShip/node_modules/express/lib/router/index.js:271:10)
    at Function.handle (/Users/dfrank/code/projects/battleShip/node_modules/express/lib/router/index.js:176:3)
    at router (/Users/dfrank/code/projects/battleShip/node_modules/express/lib/router/index.js:46:12)
    at Layer.handle [as handle_request] (/Users/dfrank/code/projects/battleShip/node_modules/express/lib/router/layer.js:95:5)
    at trim_prefix (/Users/dfrank/code/projects/battleShip/node_modules/express/lib/router/index.js:312:13)
    at /Users/dfrank/code/projects/battleShip/node_modules/express/lib/router/index.js:280:7
    at Function.process_params (/Users/dfrank/code/projects/battleShip/node_modules/express/lib/router/index.js:330:12)
    at next (/Users/dfrank/code/projects/battleShip/node_modules/express/lib/router/index.js:271:10)
    at session (/Users/dfrank/code/projects/battleShip/node_modules/express-session/index.js:438:7)

How do I access the session object that was initially created? Let me know if I can provide any more info. Thanks!

Diana F.
  • 31
  • 3
  • Who is making the API calls and are they retaining the cookie from one request to the next? – jfriend00 Oct 11 '16 at 04:08
  • @jfriend00 so the api calls are being done through client side of a react app to the server. i'm not sure if they're retaining the cookie, how would i figure that out? when i set up the sessions, i have a cookie set with a max age 6000. – Diana F. Oct 11 '16 at 04:23
  • If it's an ajax call from browser-based javascript and the browser is not configured to drop or block cookies and the session cookie path is compatible with different pages and the cookie expiration is long enough and you're using the same origin for each API call, then the cookies are maintained automatically. – jfriend00 Oct 11 '16 at 04:29
  • You can examine the cookie sent with each request in the network tab of the Chrome debugger to see exactly what it is sending to the server. – jfriend00 Oct 11 '16 at 04:31
  • 1
    So its not an ajax call, i'm actually using fetch, so for instance: fetch('/api/setShips',{ method: 'post', body: coordinates, headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' } }).then(response => response.json()).then(result => { this.setState({ cpuCoordinates: result.response, status: 'waiting_for_player_turn' }) }) the weird thing is, between the first and second request, different cookies are being sent – Diana F. Oct 11 '16 at 04:41
  • `fetch()` from a browser is an Ajax call. `fetch()` is just a newer interface than `XMLHttpRequest`, but still an Ajax call. You need to examine the cookies the browser is sending with both requests and set some breakpoints in the session handling code in your server to see what it sees. – jfriend00 Oct 11 '16 at 05:12
  • I am having this problem with server side rendering with node-fetch – Daniel Thompson Jan 16 '19 at 01:03
  • Does this answer your question? [Make Axios send cookies in its requests automatically](https://stackoverflow.com/questions/43002444/make-axios-send-cookies-in-its-requests-automatically) – Tomerikoo Jul 19 '21 at 11:35

0 Answers0