mongodb - How to create sessions in node.js -


in node.js / mongodb want create easy session , give page can know if user logged in or not. want know if can access page or not, how this? how set session , how value check if have redirect user.

thanks lot!

use express session.

it's worth taking @ passport makes implementing authentication in node.js easy.

express session example:

var express = require('express'); var session = require('express-session'); var app = express();  // make sure defined before of routes // make use of session. app.use(session({   secret: 'keyboard cat',    cookie: { maxage: 60000 },   resave: false,   saveuninitialized: false }));  // access session req.session app.get('/login', function(req, res) {   req.session.user = 1;   res.end('user 1 logged in, please go /discussion page.'); });  app.get('/discussion', function(req, res) {   var sess = req.session;   if (typeof sess.user === 'undefined') {      res.redirect('/login');   } else {     res.setheader('content-type', 'text/html');     res.write('<p>user: ' + sess.user + '</p>');     res.write('<p>expires in: ' + (sess.cookie.maxage / 1000) + 's</p>');     res.end();   } }); 

Comments

Popular posts from this blog

java - nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet Hibernate+SpringMVC -

sql - Postgresql tables exists, but getting "relation does not exist" when querying -

asp.net mvc - breakpoint on javascript in CSHTML? -