I see that I am getting a new session created in mongodb with a new session ID every time when I am clicking on the get or update button. When I inspect the Network tab in the browser, I see that a new session ID is attached to the Cookie in Request header every time the get or update button is pressed. Please advise how to have just one session persist with the same session ID in the request cookie header so that the count is based off the last value and not start from 1 always. Below is the code:
app.js
const express = require('express')
const mongoose = require('mongoose')
const cors = require('cors')
const session = require('express-session')
const MongoStore = require('connect-mongo')(session) // used for session store
const app = express()
const dbString = 'mongodb://localhost:27017/sampledb'
const dbOptions = {useNewURLParser: true, useUnifiedTopology: true}
const connection = mongoose.createConnection(dbString, dbOptions)
// middleware
app.use(cors({origin: true, credentials: true}))
app.use(express.json())
app.use(express.urlencoded({extended:true}))
const sessionStore = new MongoStore({
mongooseConnection: connection,
collection: 'sessions'
})
app.use(session({
secret: 'some secret',
resave: false,
saveUninitialized: false,
store: sessionStore,
cookie: {maxAge: 1000*60*60*24*30}
}))
app.get('/', (req, res, next) => {
console.log("get:", req.session)
if (req.session.viewCount) {
req.session.viewCount = req.session.viewCount + 1
} else {
req.session.viewCount = 1;
}
res.json({getCount: `You have visted this page ${req.session.viewCount} times`})
})
app.put('/update', (req, res, next) => {
console.log("update:", req.session)
if (req.session.viewCount % 2 == 0) {
req.session.viewCount +=1
} else {
req.session.viewCount -= 1;
}
res.json({getCount: `You have visited this page ${req.session.viewCount} times`})
})
app.listen(3002)
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button onclick="myfunction()"> Get </button>
<button onclick="myfunction2()"> Update </button>
<script>
const myfunction = async () => {
const resp = await fetch('http://localhost:3002', {
method: 'GET',
credentials: 'include',
headers: {
'Content-Type': 'application/json'
})
const data = await resp.json()
console.log(data) // it is always logging {getCount: "You have visted this page 1 times"}
}
const myfunction2 = async () => {
const resp = await fetch('http://localhost:3002/update', {
method: 'PUT',
credentials: 'include',
headers: {
'Content-Type': 'application/json'
}
})
const data = await resp.json()
console.log(data) // it is always logging {getCount: "You have visted this page NaN times"}
}
</script>
</body>
</html>
question from:https://stackoverflow.com/questions/65713684/how-to-get-only-one-session-when-using-express-session