NodeJs and ExpressJs cannot set cookies

Can you help me create a cookie because I cannot make it work. I would like to set and create cookies after the user logs in, but I do not know what is wrong with my codes. Thanks guys.

Here is my code, if you think there is another error or code correction, can you help me fix this? Thank you, guys.:)

app.js

//deps var express = require('express'); var app = express(); var redis = require('redis'); var client = redis.createClient(); var delcookie = function(req, res) { res.clearCookie('login_token'); res.redirect('/'); }; var setcookie = function(req, res) { res.cookie('login_token', +new Date(), { maxAge: 3600000, path: '/' }); res.redirect('/'); }; //configs app.use(express.bodyParser()); app.use(express.cookieParser()); app.use(app.router); client.on('error', function (err) { console.log('Error: ' + client.host + ':' + client.port + ' - ' + err); }); app.get('/', function (req, res) { res.sendfile(__dirname + '/index.html'); }); app.get('/login/', function (req, res) { res.sendfile(__dirname + '/login.html'); }); app.get('/register/', function (req, res) { res.sendfile(__dirname + '/register.html'); }); app.get('/restricted/', function (req, res) { res.sendfile(__dirname + '/restricted.html'); }); app.get('/logout/', delcookie, function (req, res) { res.sendfile(__dirname + '/logout.html'); }); //post app.post('/login/', function (req, res) { //res.sendfile(__dirname + '/restricted.html'); client.hmget( req.body.user.username, 'password', function (err,pass) { if ( (!err) && pass && pass == req.body.user.password ){ res.redirect('/restricted/', setcookie); } else if ( pass == false) { res.redirect('/register/'); } else { res.redirect('/login/'); } }); }); app.post('/register/', function (req, res) { client.hmset(req.body.user.username, 'password',req.body.user.password, 'fname',req.body.user.fname, 'lname', req.body.user.lname, 'password', req.body.user.password, 'email', req.body.user.email, 'mobile', req.body.user.mobile, redis.print); res.write('Successfully Registered'); }); app.listen(80); 
+2
javascript cookies session express
source share
1 answer

To use cookies, you must look at the Express cookieSession . Documents are here: http://expressjs.com/api.html#cookieSession

Refresh (I can't check it right now, so this is from what I remember):

You can add the cookieSession middleware and specify the settings for your cookie with something like:

 app.use(express.cookieSession({ cookie: { path: '/', maxAge: 3600000 } })); 

Then, when your user logs in, you can set the login token in the session using req.session.login_token = 'login_token'; .

And when your user logs out, you can clear the session by doing req.session = null; .

In the middleware authentication you can check if the login token is set in the session to check if the user is authenticated.

+1
source share

All Articles