Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$cookieStore.get() return undefined in angularjs

I'm writing a cookie from a server through the response and it's fine the problem is when I try to read the same cookie using angularJs $cookieStore.get() returns always 'undefined', I have debugged with the developer tools using chrome and the cookie is there,

console.log($cookieStore.get("r"));

the $cookieStore seems to be injected and running ok, I'm just wondering why angularJs can't read the cookie.

r: undefined

enter image description here

Edit:

I tried with $cookies service and I get undefined as well.

I send the cookie in the server side without any problem, I'm getting the cookie in chrome developer tools

I'm using Service Stack and the code is the following:

public override object Logout(IServiceBase service, ServiceStack.ServiceInterface.Auth.Auth request)
        {
            var resp = service.RequestContext.Get<IHttpResponse>();
            resp.Cookies.AddCookie(new Cookie { Name = "r", Path = "/", Value = "from server", HttpOnly = false, Discard = false, Expires = DateTime.Now.AddHours(12) });
            return base.Logout(service, request);
        }
like image 398
pedrommuller Avatar asked Oct 16 '13 04:10

pedrommuller


2 Answers

I think $cookieStore is only meant to be used by itself, was 'r' set somewhere else? The docs say it provides a key/value store backed by cookies, not direct access to cookies. When I set 'myValue' to 'jason' it stores %22jason%22 (fiddle). This means you can set values to javascript objects if you want and the cookieStore will serialize and deserialize them for you.

enter image description here

Try using $cookies instead where you can just set properties and the values aren't encoded (fiddle):

enter image description here

    $scope.setValue = function() {
        $cookieStore.put("myValue", $scope.value);
    };

    $scope.getValue = function() {
        $scope.value = $cookieStore.get('myValue');
    };

    $scope.setCookieValue = function() {
        $cookies.otherValue = $scope.value;
    };

    $scope.getCookieValue = function() {
        $scope.value = $cookies.otherValue;
    };
like image 147
Jason Goemaat Avatar answered Oct 27 '22 13:10

Jason Goemaat


Yes @Pedro is right in .NET ,for example, when doing an authentication with HttpCookie by default the attribute HttpOnly is true and in javscript -> document.cookie cant find the cookie you just saved to the browser.

It worked for me by setting to false HttpOnly when saving the cookie.

like image 41
user3419843 Avatar answered Oct 27 '22 13:10

user3419843