I have an Angular 7 app connecting to a Express API backend and the session doesn't seem to persist.
In Express I have the following endpoint:
router.get('/getsession', function(req, res) {
console.log(`Session ID: ${req.session.id}`);
res.status(200).json({ sessionid: req.session.id });
});
Here's an example of the output for two consecutive runs of /getsession
:
Session ID: NMi8AXhX1wf9xui0WDFwENZ_3QON_iYN
Session ID: pNWcPTeJVlC8rKySw6ty5xSPa9sSME8x
I've enabled the Credentials header for Express, so it will accept it:
const cors = require("cors");
app.use(cors({
credentials: true,
}));
And I've also enabled withCredentials
for Angular HttpClient
, so that it will send the cookie along with the POST request:
API_URL: string = "http://localdev.com:4200/api";
options = {
headers: new HttpHeaders({
'Content-Type' : 'application/json',
'Cache-Control': 'no-cache',
'Credentials': 'same-origin'
}),
withCredentials: true,
}
getSessionInfo() {
return this.http.get(`${this.API_URL}/users/getsession`, { withCredentials: true })
.pipe(
catchError(this.handleError)
)
}
There's an Angular proxy from localhost:4200
to localhost:4044
so the API requests can be processed.
Any help would be appreciated, thanks in advance :)
EDIT: Interestingly enough, the cookie is being passed properly onto Express, however it's still creating a new session for each request. The following is the result of req.session
when calling the /getsession
endpoint.
{ 'if-none-match': 'W/"b8-afvqPuftgTLN3Wn5o/ZQx8jUsv0"',
cookie: '_ga=GA1.2.1851469997.1544357368; _gid=GA1.2.1246771476.1544357368; _gat_gtag_UA_99682244_1=1',
'accept-language': 'en-US,en;q=0.9,bg;q=0.8,mt;q=0.7',
'accept-encoding': 'gzip, deflate',
referer: 'http://localdev.com:4200/user/register',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.80 Safari/537.36',
accept: 'application/json, text/plain, /',
connection: 'close',
host: 'localdev.com:4044' }
Session ID: XWKGlJPrzYeRBU3Hi7RIAaWpowGU6Fuz
{ 'if-none-match': 'W/"b8-mMGAHD1Tmbv1r5T+YChLkQoq988"',
cookie: '_ga=GA1.2.1851469997.1544357368; _gid=GA1.2.1246771476.1544357368; _gat_gtag_UA_99682244_1=1',
'accept-language': 'en-US,en;q=0.9,bg;q=0.8,mt;q=0.7',
'accept-encoding': 'gzip, deflate',
referer: 'http://localdev.com:4200/user/register',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.80 Safari/537.36',
accept: 'application/json, text/plain, /',
connection: 'close',
host: 'localdev.com:4044' }
Session ID: T4SnSqGfo9lOWGpiyPQS0LLJgXsRnZ4T