How to implement "login remember me" using cookies in Express.js?

I feel pretty confused, don't understand what is the difference between res.cookie and req.cookies. And even stranger, I found that if I did not set the cookie:

//The value will be: req.cookies.uid=="undefined" //instead of: req.cookies.uid==undefined 

Why does express.js create such a cookie?

If I want to implement the “remember me” function when users try to log in and set the cookie expiration time to infinity or maybe a year, how should I use cookies correctly?

I found that cookieParser only supports this thing:

 express.cookieParser("secret") 

And does not support the installation of expire / maxAge.

+4
source share
3 answers

res.cookie is actually a function with the signature res.cookie(key, value, opts) . You can use it to set client cookie values ​​/ parameters. req.cookies , req.cookies other hand, is an object that gives you the current cookie values ​​for a client. Here's an example of using cookies to track page views:

 var counter = 0; app.get('/counter', function(req, res) { res.cookie('counter', ++counter); if (!req.cookies.counter) { res.send('This is your first visit!'); } else { res.send('This is visit number '+ req.cookies.counter +'!'); } }); 

If you use express.cookieSession() middleware, you can set the general cookie default properties for the application. For example, the cookie maxAge property determines how many milliseconds a cookie expires in the future, so I set it within one hour:

 app.use(express.cookieParser()); app.use(express.cookieSession({ secret: 'secret', cookie: { maxAge: 60 * 60 * 1000 }}); // ... your middleware and routes 

Otherwise, you can set your cookie settings individually by passing the options res.cookie() object.

+15
source

I suggest you refer to the following question / answer . What you are looking for is the code below. This allowed you to set the maximum age of each cookie.

 if(remember){ req.session.cookie.maxAge = 2628000000; } 
+2
source

Here is an express intermediary that does just that: https://github.com/mdarveau/session-rememberme

0
source

All Articles