I am looking to track the number of requests sent by a browser and store it in the session. Below is the code snippet I have written:
import express from 'express';
import expressSession from 'express-session';
import path from "path";
const app = express();
app.use(expressSession({
secret:"cat keyboard",
resave:true,
saveUninitialized:true
}));
app.use((req,res,next)=>{
console.log(req.path)
console.log("before", req.session?.count)
if (req.session) {
if (req.session.count) {
req.session.count += 1;
} else {
// vistCounter += 1
req.session.count = 1;
}
} else {
console.log("no session",req.session)
}
console.log("after", req.session?.count)
next();
})
app.use(express.static('public'));
app.use((req,res,next)=>{
res.sendFile(path.join(__dirname + "/public","404.html"));
})
app.listen(1234,()=>{
console.log("server run");
});
When accessing localhost:1234, the following output is displayed:
/
before undefined
after 1
/index.css
before 1
after 2
/index.js
before 1 (it should be 2)
after 2
/favicon.ico
before 2
after 3
It appears that the browser made requests for "/", "index.css", "index.js", and "favicon.ico". However, the counter does not update between the index.css and index.js requests. The counter should increment to 2 after the index.css request, leading to a value of 2 before the index.js request adds 1 more. Instead, the counter remains at 1 during the "index.js" request. Can someone clarify why the counter is not updating after the index.css request but before the index.js request?