In Node.js, we usually use the express-session package to use and manage sessions and save the session status between the server and the client browser. So how can I achieve the expiration time of the session when the user refreshes the current page or clicks a button on the page? Similar to the session status in ASP.NET, as long as the page remains active for a certain period of time, the session will not expire. This function can be achieved through the following code. We add the following middleware to the Node.js code:
// use this middleware to reset cookie expiration time// when user hit page every timeapp.use(function(req, res, next){ req.session._garbage = Date(); req.session.touch(); next();});In this way, every time a request comes, the middleware will re-modify the expiration time of the session to achieve the expected effect.
Then, add the use of session in the code:
app.use(session({ secret: 'test', resave: false, saveUninitialized: true, cookie:{ maxAge: 1000*60*60 // default session expiration is set to 1 hour }, store: new MemcachedStore({ hosts: ['127.0.0.1:9000'], prefix: 'test_' })}));The above session uses memcached as the storage method of session. For how to use memcached, please refer to this address on Github https://github.com/balor/connect-memcached
Of course, you can also use other session storage methods, such as memoryStore, redis, mongoDB, etc., and the usage methods are similar.
The above article "The implementation method of Node.js refresh session expiration time" is all the content shared by the editor. I hope it can give you a reference and I hope you can support Wulin.com more.