0
我正在使用角度$资源来访问API。在这种特殊情况下,使用自定义登录操作,以便登录用户。
为了保存身份验证后API提供的令牌,我将拦截器附加到自定义登录操作,该操作通过$ cookie简单地将令牌保存到cookie中。
我使用的是拦截器,因为我需要从应用程序的其他部分保存和更新该cookie。
问题是,cookie似乎不会持续。
如果我在保存后检查值,我可以确认它存在,但只要我的$位置发生变化(就像登录后渲染主页一样),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"
}
}
});
}
})();
这里是拦截器(即那里的console.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);
}
};
}
它永远不会太晚 – AlainIb