为了使用AngularJs检索的响应报头,并设置它的所有请求 [英] Using AngularJs in order to retrieve a header from the response and set it on all requests
问题描述
我想,以从响应的头的一个检索的 CSRF令牌并设置它的所有请求使用 Angularjs
我已成功地从使用响应拦截器的响应阅读如下:
.factory('csrfResponseInterceptor',[功能(){
返回{
回应:功能(响应){
的console.log(response.headers(X-CSRF-TOKEN'));
返回响应;
}
}
}])
但我不知道如何把它放在所有请求之后。
不知怎的,我需要使用 $ httpProvider
服务进行如下设置:
$ httpProvider.defaults.headers.common ['X-CSRF-TOKEN'] = response.headers('X-CSRF-TOKEN');
我没有设法注入 $ httpProvider
进入拦截器虽然。
可有人请一个最佳实践提供建议?
修改:这是我如何注册我的拦截器:
的.config(['$ httpProvider',函数($ httpProvider){
$ httpProvider.defaults.xsrfHeaderName ='X-CSRF-TOKEN';
$ httpProvider.interceptors.push('HTT presponseInterceptor','csrfResponseInterceptor');
}])
我觉得你可以做这样的配置功能:
的.config(['$ httpProvider',函数($ httpProvider){
$ httpProvider.defaults.xsrfHeaderName ='X-CSRF-TOKEN';
$ httpProvider.interceptors.push(函数(){
返回{
回应:功能(响应){
$ httpProvider.defaults.headers.common ['X-CSRF-TOKEN'] = response.headers('X-CSRF-TOKEN');
返回响应;
}
}
});
}]);
I am trying to use Angularjs in order to retrieve the csrf token from one of the response's header and set it on all requests.
I have managed to read it from the response using a response interceptor as follows:
.factory('csrfResponseInterceptor', [function () {
return{
response: function(response){
console.log(response.headers('X-CSRF-TOKEN'));
return response;
}
}
}])
but I am not sure how to set it on all requests afterwards.
Somehow I would need to set it using the $httpProvider
service as follows:
$httpProvider.defaults.headers.common['X-CSRF-TOKEN'] = response.headers('X-CSRF-TOKEN');
I haven't managed to inject the $httpProvider
into the interceptor though.
Can someone please provide advice on a best practice?
edit: This is how I register my interceptors:
.config(['$httpProvider', function ($httpProvider) {
$httpProvider.defaults.xsrfHeaderName = 'X-CSRF-TOKEN';
$httpProvider.interceptors.push('httpResponseInterceptor', 'csrfResponseInterceptor');
}])
I think you can do it like this in config function:
.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.xsrfHeaderName = 'X-CSRF-TOKEN';
$httpProvider.interceptors.push(function() {
return {
response: function(response) {
$httpProvider.defaults.headers.common['X-CSRF-TOKEN'] = response.headers('X-CSRF-TOKEN');
return response;
}
}
});
}]);
这篇关于为了使用AngularJs检索的响应报头,并设置它的所有请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!