I'm currently facing an issue where I am unable to access req.session from my Express app in Angular. Both the backend and frontend are deployed separately on Heroku. I have already configured CORS to handle HTTP requests 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();
});
However, I am encountering difficulty in handling or retrieving the request session as it always appears empty. While I was able to retrieve the connect.sid in my Express app when making an HTTP GET request, it does not persist when another request is made in Angular. Consequently, each time the Angular app is refreshed, the session ID also gets refreshed. I require the cookie to persist so that I can utilize it for a POST request (e.g., initiating an HTTP GET request to Angular with the response being a CSRF token, followed by a subsequent POST request using the requested CSRF token for login). Since every session ID is different for each request, the CSRF token becomes invalid. All Express sessions are stored in MongoLab through the 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}
}));
The HTTP GET and POST methods in my Angular App are functioning correctly, indicating that CORS has been properly configured. Upon inspecting the response header when accessing the route URL ('login') in Angular to initiate the HTTP GET request, I noticed that the cookies (cookies.sid) were set in the header. However, I am unsure how to store this session ID from the cookies in order to use it for subsequent requests in the Angular app (such as logging in).