I've been scratching my head for this one for hours now yet still haven't found the cause or solution.
Basically I have an Angular.js frontend that tries to log users in (with ngCookies
on Angular.js 1.3.15) by communicating with an authentication API endpoint in the backend. Upon success, my code should redirect the user to another page.
So the login code looks something like:
auth.login($scope.user).success(function() {
$state.go('overview');
});
where auth
is a service that has a login
method which simply sends an POST request to the backend. $state.go('overview')
will do the redirect. This code should be ok as I get HTTP200 back from the server given I supply the correct user credentials. However, the browser won't redirect me to the overview page because it still thinks I'm not logged in unless I refresh the page.
The code that checks if the current user is logged in uses a helper method called getToken()
, where I use ngCookies
to retrieve a cookie named USER_SESSION
. And this method is where I think the problem is.
The method itself is simply
auth.getToken = function() {
return $cookies.USER_SESSION;
};
However it always returns undefined
even when the USER_SESSION
cookie exists in the browser.
Some testing I did (on a remote testing server so accessing cookies in localhost
shouldn't be a concern):
auth.getToken = function() {
console.log($cookies);
console.log($cookies.USER_SESSION);
return $cookies.USER_SESSION;
}
The results of console.log
:
// Before login:
Object {...} // No USER_SESSION, this is good
undefined
// After hitting the login button, browser sends AJAX request,
// server returns HTTP200 response with Set-Cookie in the header:
Object {USER_SESSION: ""aa21fcd..."", ...} // UESR_SESSION exists, good
undefined // ???
// After refreshing the page:
Object {USER_SESSION: ""09b4tk..."", ...}
"09b4tk..."
Are the double quotes the problem here? I thought so initially, but after refreshing the page, $cookies
returns the same thing (same double quotes but a different USER_SESSION
value) and $cookies.USER_SESSION
would have the correct value, and user would be on the overview page.
Does this mean Set-Cookie
in the HTTP response header needs a page refresh to take effect?
Thanks!
P.S. Same problem occurs with cookieStore
.