角度$cookies不持久

Angular $cookies not persisting

本文关键字:不持久 cookies 角度      更新时间:2023-09-26

我正在使用角度$resource来访问API。在这种特殊情况下,使用自定义登录操作,以便登录用户。

为了在身份验证后保存 API 提供的令牌,我将拦截器附加到自定义登录操作,该操作只是通过 $cookies将令牌保存到 cookie。

我正在使用拦截器,因为我需要从应用程序的其他部分保存和更新该cookie。

问题是 cookie 似乎没有持续存在。

如果我在保存后检查值,我可以确认它在那里,但是一旦我的$location被更改(例如在登录后呈现主页时),cookie就会消失。

有什么想法吗?

谢谢,D。

这是我的登录服务,它使用自定义登录操作和拦截器

(function() {
    'use strict';
    //Login Service
    // Authenticates a user
    angular
    .module('console')
    .factory('LoginService', LoginService);    
        LoginService.$inject = ['$resource', 'Config', 'UserInfoInterceptor'];
            function LoginService($resource, Config, UserInfoInterceptor) {
                return $resource(Config.api_url + '/auth/', {},
                    {
                        login: {
                        method: 'POST',
                        url: Config.api_url + '/auth/login',
                        data: {type: "passwd"},
                        interceptor: UserInfoInterceptor,
                        headers: {
                        "accept": "application/json",
                        "content-Type": "application/json;odata=verbose"
                    }
                }
            });
    }
})();

这是拦截器(该控制台.log实际上写入了cookie值),但是在转到其他位置后立即丢失。

(function() {
  'use strict';
  angular
    .module('console')
    .factory('UserInfoInterceptor', UserInfoInterceptor);
    UserInfoInterceptor.$inject = ['$resource', 'Config', '$q', '$location', '$cookies'];

    function UserInfoInterceptor($resource, Config, $q, $location, $cookies) {    
        return {
                // Save the received token 
                'response': function (response) {
                    var now = new Date();
                    // this will set the expiration to 30 days
                    var exp = new Date(now.getFullYear(), now.getMonth()+1, now.getDate());
                    // Set the cookie
                    $cookies.put('token', response.data.token, {expires: exp});
                    //This actually works!!
                    console.log($cookies.get('token'));
                    return response;
                },
                // Whatever is the failure, throw the user to the login page
                'responseError': function (response) {
                    if (response.status === 401 || response.status === 403) {
                        $location.path('/login');
                    }
                    return $q.reject(response);
                }
            };    
    }

这为时已晚,但我认为此修复程序也可能帮助其他人。

我尝试在$cookiesProvider中设置cookie路径,如下所示,

xxApp.config(['$cookiesProvider', function ($cookiesProvider) {
     $cookiesProvider.defaults.path = '/'; 
}]);