This is my code:
const express = require('express')
const session = require('express-session')
const compression = require('compression')
const sessionOptions = {
secret: '123',
name: 'test',
resave: true,
saveUninitialized: false,
rolling: true,
cookie: {
httpOnly: true,
maxAge: 1000 * 1800, // 30min
secure: true
}
}
const app = express()
app.use(session(sessionOptions))
app.use(compression())
app.use(express.json())
app.use(express.urlencoded({ extended: false }))
app.get('/', (req, res) => {
console.log(req.session)
res.json({
id: req.sessionID,
data: req.session.data
})
})
app.get('/login', (req, res) => {
req.session.data = 'asdasdasdasd'
res.end(req.sessionID)
})
app.listen(3000, () => {
console.log(`Server running at http://127.0.0.1:3000`)
})
Then I visited /
and kept refreshing the page, but each time the 'sessionID' was different.
When I first access /login
and then access /
, the result is:
{
"id": "8Z9bb5B6lATMe1sAIT_8QgY07YvOlr8P"
}
The output of the server is:
Session {
cookie: {
path: '/',
_expires: 2023-12-28T06:35:36.057Z,
originalMaxAge: 1800000,
httpOnly: true,
secure: true
}
}
I checked the network panel of the browser console and found that the Set-Cookie
field never appeared in the response header, even though I modified req.session
on the server side.
I just want to implement the function of using session to record user login status.
Did I write something wrong somewhere? Humbly seeking advice, greatly appreciated!
I checked the server console output, browser developer tool request messages, and using Wireshark to crawl HTTP request messages. I hope someone can tell me the correct usage of express-session
This is a very interesting question, it makes me laugh heartily. In the configuration of the express-session
middleware, I set the value of sessionOptions.cookie.secure
to true
, which means only when I have to use HTTPS.