Created
August 30, 2018 04:38
-
-
Save devarajchidambaram/77794d6e61beed6ab0abf7c9f3665279 to your computer and use it in GitHub Desktop.
Express session in nodejs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var express = require('express'); | |
var cookieParser = require('cookie-parser'); | |
var session = require('express-session'); | |
var app = express(); | |
app.use(cookieParser()); | |
//For every request the session id is assigned if there is no session id | |
//We can attach fields in req.session.key = value pair | |
app.use(session({ | |
secret: "Shh, its a secret!" | |
})); | |
app.get('/', function (req, res) { | |
console.log("req sid", req.sessionID) | |
console.log('cookies', req.cookies) | |
if (req.session.page_views) { | |
req.session.page_views++; | |
res.send("You visited this page " + req.session.page_views + " times"); | |
} else { | |
req.session.page_views = 1; | |
res.send("Welcome to this page for the first time!"); | |
} | |
}); | |
app.get('/login', function (req, res) { | |
if (req.query.username === 'admin' && req.query.password === 'admin') { | |
req.session.username = 'admin'; | |
req.session.password = 'admin'; | |
res.send("you are logged in"); | |
} else { | |
res.send("you are not logged in , invalid credencials"); | |
} | |
}); | |
app.get('/home', function (req, res) { | |
if (req.session.username === 'admin') { | |
res.send("welcome to the home page"); | |
} else { | |
res.send("you are not authenticated please login first"); | |
} | |
}); | |
app.listen(3000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment