I'm trying to access the req.session from my express app to angular (backend and frontend deployed separately in heroku). I already set up the CORS to handle http request from angular to my express app.
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", '*');
res.header("Access-Control-Allow-Credentials", true);
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header("Access-Control-Allow-Headers", 'Origin,X-Requested-With,Content-Type,Accept,content-type,application/json,X-XSRF-TOKEN,CSRF-Token,X-CSRF-Token');
next();
});
and I'm having a trouble handling or getting request session as it is always empty. I was able to get the connect.sid to to my express app when making a http get but it is not persisting when making another request in angular, so everytime I refresh the angular app the session ID will be refreshed also. I need the cookie to persist so I can use it when making a post request (i.e. making an http get request to angular, "Response will be csrf token" then making another http post request using the requested csrf token for login, but since every session id will be different on each request the csrf token will be invalid. Every express sessions is stored in mongo lab through connect-mongo npm module.
app.use(session({
secret : process.env.sessionKey,
httpOnly: true,
resave : true,
saveUninitialized: true,
store : new mongoStore({ mongooseConnection: mongoose.connection }),
cookie : { maxAge: 60 * 60 * 1000}
}));
Http get post in my Angular App is already working, so CORS is set properly. When I checked the response header when I access the route url (login) in angular that will make the Http get request call I notice that the cookies (cookies.sid) was set on header but I don't how would I store it so I can use this cookies session ID for my next request in angular app (such as post login)
If you want to read cookie that is saved in browser you can create following function wherever you require:
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return null;
}
to check the cookie name
go to Application
tab in developer console of your browser in this case I guess connect.sid
. Get the name and call
getCookie(<cookie-name>); you can use this value further.