【发布时间】:2015-08-16 22:25:33
【问题描述】:
我创建了一个使用 API 的 AngularJS 网站。此 API 提供了一些功能,例如身份验证 (Oauth)。
当API返回401错误时,说明access_token已经过期,需要用refresh_token刷新。
我在 AngularJS 中创建了一个拦截器。它的目标是检查API返回的结果是否为401错误,如果是,则必须刷新令牌,然后处理之前被拒绝的请求。
问题在于拦截器创建了一个无限循环。在初始请求第二次失败后,它应该停止但它没有。
angular.module('myApp')
.factory('authInterceptor', function ($rootScope, $q, $window, $injector) {
return {
// If the API returns an error
'responseError' : function(rejection) {
// If it's a 401
if (rejection.status == 401) {
var deferred = $q.defer();
$injector.get('$http').post('http://my-api.local/api/oauth/token', {
grant_type : 'refresh_token',
client_id : 'id',
client_secret : 'secret',
refresh_token : $window.sessionStorage.refresh_token
}, {
headers : {
'Content-Type' : 'application/x-www-form-urlencoded'
},
transformRequest : function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
}
})
// New token request successfull
.success(function(refreshResponse) {
// Processing the failed request again (should fail again because I didn't saved the new tokens)
$injector.get('$http')(rejection.config).success(function(data) {
deferred.resolve(data);
})
.error(function(error, status) {
deferred.reject();
});
return deferred.promise();
})
// New token request failure
.error(function(error, status) {
deferred.reject();
// $location.path('users/login');
return;
});
}
// If it's another errorenter code here
else
return rejection;
}
}
});
所以这段代码:
- 在第一个请求失败时启动
- 刷新令牌
- 重试请求但再次失败(
- 刷新令牌
- 重试请求但再次失败
- 刷新令牌
- 重试请求但再次失败
- 等等……
【问题讨论】:
-
这看起来不对:
return deferred.promise();。您应该只是返回承诺对象return deferred.promise而不是尝试执行它。
标签: angularjs angular-http-interceptors