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
Post a Comment