设置默认值的头,但AngularJS不使用它,在一个特定的请求 [英] Set defaults header on AngularJS but don't use it on one specific request

查看:230
本文介绍了设置默认值的头,但AngularJS不使用它,在一个特定的请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关发送的OAuth2令牌,我设置的默认值在AngularJS头是这样的:

  $ http.defaults.headers.common ['授权'] ='承载'+的access_token;

这个伟大的工程,但我不需要这个头(我得到一个错误)对于一个特定的请求。

有没有执行该请求时,违约头排除的一种方式?

谢谢!

解决

感谢 Riron 获取我一个正确的道路上。这里的答案:

  $ HTTP({
    方法:GET,
    网址:'HTTP://.../',    transformRequest:功能(数据,headersGetter){
        变种头= headersGetter();        删除标题['授权'];        返回头;
    }
});


解决方案

当你让你的电话与$ HTTP,您可以直接在您的要求配置为他们提供覆盖默认标题:

  $ HTTP({方法:GET,网址:'/ someUrl',头:{'授权':'的NewValue'}})成功();

否则,你可能在你的$ HTTP配置使用 transformRequest 参数变换你的要求,依然​​。见文件:


  

transformRequest - {功能(数据,headersGetter)|阵<功能(数据,headersGetter)GT;} - 变换
  功能或这些功能的阵列。变换函数接受
  HTTP请求正文和标题,并返回其转化
  (通常是序列化)版本。


这样你可以删除一个头单个请求之前,它被发送:

  $ HTTP({方法:GET,
       网址:'/ someUrl',
       transformRequest:功能(数据,headersGetter){//这里头改变}
})。成功();

For sending OAuth2 token I am setting up defaults header on AngularJS like this:

$http.defaults.headers.common['Authorization'] = 'Bearer ' + access_token;

This works great but I don't need this header (I get an error) for one specific request.

Is there a way of excluding defaults header when performing that request?

Thanks!

SOLVED

Thanks to Riron for getting me on a right path. Here's the answer:

$http({
    method: 'GET',
    url: 'http://.../',

    transformRequest: function(data, headersGetter) {
        var headers = headersGetter();

        delete headers['Authorization'];

        return headers;
    }
});

解决方案

When you make your call with $http, you can override defaults headers by providing them directly in your request config:

$http({method: 'GET', url: '/someUrl', headers: {'Authorization' : 'NewValue'} }).success();

Otherwise you could transform your request using the transformRequest parameter, still in your $http config. See doc :

transformRequest – {function(data,headersGetter)|Array.<function(data, headersGetter)>} – transform function or an array of such functions. The transform function takes the http request body and headers and returns its transformed (typically serialized) version.

This way you could delete an header for a single request before it's being send:

$http({method: 'GET', 
       url: '/someUrl', 
       transformRequest: function(data,headersGetter){ //Headers change here } 
}).success();

这篇关于设置默认值的头,但AngularJS不使用它,在一个特定的请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆