你好我've created basic angularJS interceptor which should add token before every request. Token come from localforage and I'我确定它在那里,因为我在拦截器中它是 console.log
它在浏览器控制台中显示 . 当我尝试注销它时说401因为令牌不存在请求拦截器看起来很好并且它不会在控制台中引起任何错误 . 我知道请求中没有令牌,因为我在chrome控制台的网络选项卡中检查了它 .
拦截器代码:
(function () {
'use strict';
angular
.module('app')
.factory('authInterceptorService', Factory);
Factory.$inject = ['$q', '$injector', '$localForage'];
function Factory ($q, $injector, $localForage) {
return {
request: function(config) {
config.headers = config.headers || {};
if(config.url.indexOf('v1') !== -1) {
$localForage.getItem('authorization')
.then(function (authData) {
if (authData) {
config.headers.Authorization = 'Bearer ' + authData.token;
console.log('theoretically i added token: ' + authData.token);
return config;
}
}, function () {
console.log("error with getting authorization localForage in interceptor");
}
);
}
return config;
},
responseError: function(rejection) {
if (rejection.status === 401) {
$localForage.clear().then(function() {
$rootScope.$emit('localForageUpdated');
});
}
}
};
}
})();
它不会为每个请求添加令牌 . Console.log
这是应该为每个请求添加令牌的行之后正在按预期工作正常值:
理论上我添加了令牌:eyJhbGciOiJIUzI1NiJ9.eyJpZCI6MSwic2VjcmV0IjoiMmM2ZGNmNmYyNWZjOThjZDdiMjk4OTY2MDg2MTEzMjIifQ.5w-eCNnsWpkp-Ztpx8gpjeZ2AVNCRtbb1Pl3Iv3veLI
为什么我的拦截器不会为每个请求添加令牌?
在我的SPA的早期版本中,我在登录服务中有成功登录功能 $http.defaults.headers.common.Authorization = 'Bearer ' + response.data.data.attributes.token;
并且它正常工作 . 现在,当我的SPA更大时,我决定将其与我的登录功能分开 .
我认为这个问题可能与 config.headers
有关 . 也许它应该是 params
或者其他什么?请快速帮助 .
EDIT
我对我的代码做了一些更多的debbugin,我发现了一些非常有趣的东西 . 当我addiotionaly console.log(config)
我看到实际上这个令牌在 config
对象中:
headers:
Accept:
"application/json, text/plain, */*"
Authorization:
"Bearer eyJhbGciOiJIUzI1NiJ9.eyJpZCI6MSwic2VjcmV0IjoiNzk5YThjYzkxYjI2NTdiYWI1ZGNiMzVkNWU3YzVlYmIifQ.RR00Y6LmDuSpePoYlm775AzhbTBIlO93OXnU9P1EHnw"
但是,请求标头上的网络选项卡中仍然没有授权标头,您可以在此处看到:
EDIT2 这里的错误是我在承诺解析之前返回配置为charlietfl在下面的评论部分中提到 . 所以我尝试在 $localForage
之前使用 return
并删除 return config;
. 我的SPA停止渲染,所以我尝试使用_1665822这样:
return {
request: function(config) {
config.headers = config.headers || {};
var deferred = $q.defer();
if(config.url.indexOf('v1') !== -1) {
$localForage.getItem('authorization')
.then(function (authData) {
if (authData) {
config.headers.Authorization = 'Bearer ' + authData.token;
console.log('theoretically i added token: ' + authData.token);
console.log(config);
deferred.resolve(config);
}
}, function () {
console.log("error with getting authorization localForage in interceptor");
deferred.resolve(config);
}
);
}
return deferred.promise;
},
但它也会导致停止渲染我的SPA视图 . 通常它会在我删除 return config;
时停止渲染,为什么?它现在应该工作正常..
我只需要在上面的代码示例中为这两个条件添加else,并在那里使用 deferred.resolve(config);
. 现在一切正常 .