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

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

问题描述

为了发送 OAuth2 令牌,我在 AngularJS 上设置默认标头,如下所示:

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?

谢谢!

感谢 Riron 让我走上正确的道路.答案如下:

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;
    }
});

推荐答案

当您使用 $http 进行调用时,您可以通过直接在请求配置中提供它们来覆盖默认标头:

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();

否则你可以使用 transformRequest 参数转换你的请求,仍然在你的 $http 配置中.见文档:

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

transformRequest – {function(data,headersGetter)|Array.} – 转换函数或此类函数的数组.变换函数取http 请求正文和标头并返回其转换后的(通常是序列化的)版本.

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天全站免登陆