I am trying to set up session variables that would persist between routes.
Problem is, that doesn't seem to happen. When I make a post request, the session variable is updated accordingly - however when trying a different get route via postman (and checking console output), the variable is empty
Here's the code:
const express = require('express')
const session = require('express-session')
const bodyParser = require('body-parser')
const app = express()
app.use(session({
secret: 'test one',
resave: false,
saveUninitialized: true,
name: "mycookiesession",
cookie: { secure: false }
}))
let mySession
app.use(function (req, res, next) {
mySession = req.session
mySession.basket = []
next()
})
app.get('/basket', function (req, res) {
console.log(mySession.basket)
res.send(mySession.basket)
})
app.post('/basket/add', function (req, res) {
mySession.basket = [0, 1, 2]
console.log(mySession.basket)
res.send('null')
res.status(201).end()
})
app.listen(3000, function () {
console.log('Example app listening')
})
What am I doing wrong? I just need to see the value added to the basket by post:basket/add when retrieving the var in the get:basket route
Cheers
CodePudding user response:
You have a middleware the sets basket = []
in your session for every incoming request. This middleware is executed for every request, because the app.use(function ...)
command does not specify a path.