Gebruik Express.js-sessie .
Het is ook de moeite waard om Passport.js te bekijken wat het implementeren van authenticatie in Node.js heel eenvoudig maakt.
Express.js-sessievoorbeeld:
var express = require('express');
var session = require('express-session');
var app = express();
// Make sure this is defined before any of your routes
// that make use of the session.
app.use(session({
secret: 'keyboard cat',
cookie: { maxAge: 60000 },
resave: false,
saveUninitialized: false
}));
// Access the session as req.session
app.get('/login', function(req, res) {
req.session.user = 1;
res.end('User 1 is logged in, please go to the /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();
}
});