Gabriel Matusevich
Gabriel Matusevich

Reputation: 3855

AngularJS $cookies, getting undefined

I'm trying to retrieve Cookies using the $cookies service provided by ngCookies but I keep getting 'undefined', I really don't know what it's wrong... I can clearly see the cookie displayed in the Dev Console in Chrome. AND I also set a XSRF-TOKEN cookie and Angular's $http is NOT including it as a Header (X-XSRF-TOKEN) which I think it's the same problem.

Laravel by default encrypts Cookies and are extremely long, could that be it?

If I set a cookie with the $cookies service, it appears and I can retrieve it withou issue, so the $cookies service is working.... :P

angular.module("MachinatorApp.Services.SectionService", [])
    .factory("SectionService", ["$http", "$cookies", function($http, $cookies) {

        console.log($cookies.laravel_session);

        var doRequest = function(action, id) {

            var params = $.param({
                "action"    : action, 
                "id"        : id                  
            });

            return $http({
                method      : 'POST',
                url         : "/Sections/" + action,
                data        : params,
                headers     : {'Content-Type': 'application/x-www-form-urlencoded'}
            });

        }

        return {
            sections: function(action, id) {
                return doRequest(action, id);
            }
        }

    }]);

Upvotes: 1

Views: 2096

Answers (1)

Gabriel Matusevich
Gabriel Matusevich

Reputation: 3855

I found out what the solution was by looking a the Laravel API Documentation, Cooke::make() by default sends a HttpOnly cookie, that's why I could not read it from Angular, Adding false to the httpOnly parameter fixes the issue, Although Now I think it's just safer to leave it http only and read from the header's cookies.

http://laravel.com/api/4.1/

search for Cookie, click CookieJar, make method

Cookie::make("XSRF-TOKEN", Session::token(), 0, null, null, null, false))

This sends a NON HTTP ONLY Cookie which you can read from angularJS

Upvotes: 1

Related Questions