0
您好,我希望使用外部API来收集所有当前的货币汇率。我的前面是基于令牌的,我在localForage中存储了令牌,它只是异步localStorage。在angularJS中添加一个例外默认头文件
//this execute after every page refresh
$localForage.getItem('authorization')
.then(function(authData) {
if(authData) {
$scope.authentication.isAuth = true;
$http.defaults.headers.common.Authorization = 'Bearer ' + authData.token;
//set authentication variable to true and add token to every request after page refresh
}
}, function(){
console.log("error with getting authorization localForage after refresh");
}
);
//this execute after custom event emitted after success login response
$rootScope.$on('localForageUpdated', function(event){
$localForage.getItem('authorization')
.then(function(authData) {
if(authData) {
$http.defaults.headers.common.Authorization = 'Bearer ' + authData.token;
$scope.authentication.isAuth = true;
//set authentication variable to true and add token to every request after page refresh
} else {
$scope.authentication.isAuth = false;
}
}, function(){
console.log("error with getting authorization localForage on event");
}
);
});
因此,这基本上是在每个后端请求之前添加包含标记的标头。
不幸的是,当我尝试从外部API下载所有当前的汇率我获得以下错误:
Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.
这是由于事实上我说头与我的令牌。我可以在注册$http.defaults.headers.common.Authorization = 'Bearer ' + authData.token;
时以某种方式添加异常吗?
您可以编写一个http拦截器并使用if-else设置auth头文件(即基于某些自定义逻辑) – harishr