[英]Angular HTTP within a HTTP Interceptor
I need to append the necessary HMAC headers to a request. 我需要将必要的HMAC标头附加到请求中。 This should not be very difficult however I am starting to get frustrated.
这应该不是很困难,但我开始感到沮丧。 What is wrong with the following code.
以下代码有什么问题。 The actual http call I am doing works;
我正在进行的实际http调用; I have run this call myself and it returns the necessary data.
我自己运行了这个调用,它返回了必要的数据。 It does not work inside the interceptor.
它在拦截器内部不起作用。
I merely want to get the current implementation working before I add whitelist or blacklist and other customizable data for this interceptor. 我只是希望在为此拦截器添加白名单或黑名单以及其他可自定义数据之前使当前实现正常工作。 This is not a question about hmac however but with promises.
这不是关于hmac的问题,而是有了承诺。
The error in this interceptor is with the entire promise line starting at $http(...). 此拦截器中的错误是整个承诺行从$ http(...)开始。 When i remove this block and use it as is (minus promise execution) it works fine.
当我删除此块并按原样使用它(减去承诺执行)它工作正常。 As soon as i uncomment the line it gets stuck in a loop and crashes chrome.
一旦我取消注释该线就会卡在一个循环中并崩溃铬。 Everywhere I have read says this is how it is done, but this clearly does not work.
我读过的每个地方都说它是如何完成的,但这显然不起作用。
function requestInterceptor(config){
var $http = $injector.get('$http');
var deferred = $q.defer();
$http.get(hmacApiEndpoint, {cache: true}).then(function(data){
console.log('HMAC - Success', data)
deferred.resolve(config)
}, function(config){
console.log('HMAC - Error', config)
deferred.resolve(config)
})
return deferred.promise;
}
return {
request: requestInterceptor
};
Does this have something to do with the fact that angulars $http promise is a different implementation than that of '$q'? 这是否与angulars $ http promise与'$ q'不同的实现有关?
It doesn't look like you are actually amending the config
with the newly obtainted HMAC. 看起来您实际上并未使用新获得的HMAC修改
config
。
Also, you'd need to protect against your requestInterceptor
intercepting the call to obtain the HMAC, thus resulting in an infinite loop. 此外,您需要保护您的
requestInterceptor
拦截调用以获取HMAC,从而导致无限循环。
And lastly, you don't need deferred
here - just return the promise produced by $http
(or $http.then()
): 最后,你不需要
deferred
- 只返回$http
(或$http.then()
)产生的承诺:
function requestInterceptor(config){
var $http = $injector.get('$http');
// just return, if this is a call to get HMAC
if (config.url === hmacApiEndpoint) return config;
return $http.get(hmacApiEndpoint, {cache: true})
.then(function(response){
console.log('HMAC - Success', response.data)
// not sure where the HMAC needs to go
config.headers.Authorization = response.data;
return config;
})
.catch(function(){
return $q.reject("failed to obtain HMAC");
});
}
return {
request: requestInterceptor
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.