问题
I am using "express": "~4.14.0"
with express-session
for saving username. Once the user is logged in, I will save the user name in req.session.authorizedUser = username
to display it in the application header.
When either the browser history is cleared or the browser is closed, I want to clear the session.
Please suggest me if there is any way to clear the session when doing any of these two operations. I have tried setting the maxAge
option for session cookies, as shown below, but it doesn't reflects good:
app.use(session({
secret: "key test",
resave: false,
saveUninitialized: true,
cookie: { secure: !true, path: '/', httpOnly: true, maxAge: null}
}));
回答1:
Since a browser doesn't notify a server when it deletes cookies (for whatever reason), there's no way of telling purely on the server side if a session should still be valid or not.
That's why most session stores have an expiry mechanism that will delete idle sessions after a specific amount of time (which is usually tied to maxAge
).
For instance, the connect-mongo session store uses MongoDB's TTL feature to remove expired sessions from the database.
Apart from taking up a bit of storage space, idle sessions aren't a problem, though. When the user logs in again, a new session will be created for them, and the old one will eventually expire and be removed from storage.
来源:https://stackoverflow.com/questions/42782761/how-to-clear-req-session-on-clearing-browser-cookies-in-node-js