Last active
February 12, 2022 09:19
-
-
Save HarshithaKP/3d9ad81138245aa7527bf385d37daba7 to your computer and use it in GitHub Desktop.
Demonstration of how user session can be persisted across redirects, with an express server and request client.
This file contains 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 session = require('express-session') | |
var app = express() | |
var r = require('request') | |
// By default cookies are disabled, switch it on | |
var request = r.defaults( { jar:true } ) | |
app.use(session({ secret: 'keyboard cat',saveUninitialized : false, resave : false, cookie: { maxAge: 60000 }})) | |
app.get('/', function(req, res, next) { | |
if(!req.session.views) { | |
req.session.views = 1 | |
console.log('first timer : '+ req.session.views) | |
res.end('first timer') | |
} else { | |
req.session.views++ | |
console.log('subsequent views: ' + req.session.views) | |
req.session.extra = "some extra data" | |
// While sessions with memoryStore may work fine with multiple requests/redirects, external | |
// stores can cause race conditions - between next client request and the store, depending | |
// on who runs faster. So save the session explicitly, prior to the response/redirect. | |
req.session.save(function(err) { | |
if(err) { | |
res.end('session save error: ' + err) | |
return | |
} | |
res.redirect('/admin') | |
}) | |
} | |
}) | |
app.get('/admin', function(req, res, next) { | |
console.log(`in redirected route, views: ${req.session.views} and extra: ${req.session.extra}`) | |
res.end('redirected response') | |
}) | |
app.listen(8000, () => { | |
request.get('http://localhost:8000', (err,res,body) => { | |
console.log(`first response : ${body}`) | |
request.get('http://localhost:8000', (err,res,body) => { | |
console.log(`second response : ${body}`) | |
}) | |
}) | |
}) |
I did the exact same thing u are doing in my project.But it is not working.
Here. Take a look at my issue please. expressjs/session#790
@HarshithaKP
I was trying to do it with async/await, and having problems.
This works fine, thanks.
How it can be done with async/await ?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output :