gpt4 book ai didi

AngularJS ngResource 不发送自定义 header

转载 作者:行者123 更新时间:2023-12-01 06:29:45 26 4
gpt4 key购买 nike

我正在尝试使用 ngResource 来查询 REST API。我需要在自定义 header 中指定我的 API key 。我试过这样:

angular.module('ApiService', ['ngResource'])

.factory('Api', ['$resource', function($resource) {

this.apiEndpoint = '';
this.apiKey = '';

return {

init: function(apiEndpoint, apiKey) {
this.apiEndpoint = apiEndpoint;
this.apiKey = apiKey;
},

get: function(collection) {
return $resource(this.apiEndpoint + 'api/1/' + collection, {},
{
get: {
method: 'JSONP',
headers: {'api_key': this.apiKey},
params: {callback: 'JSON_CALLBACK'}
}
}
).get();
}

};

}]);

然后我在我的 Controller 中使用它,例如:
app.controller('MyCtrl', function ($scope, Api, ENV) {
Api.init(ENV.apiEndpoint, ENV.apiKey);
var widgets = Api.get('widgets');
});

当我检查 XHR 时,我的自定义 header 未设置。另外,为什么在我调用空 .get() 之前 XHR 不会运行?在初始 $resource:get() 之后方法?

我还尝试在 $httpResource 中设置标题直接地:
  .config(function($httpProvider) {
$httpProvider.defaults.headers.get = {'api_key': 'abc123'};
})

但是当我检查网络请求时,这仍然没有设置自定义 header 。我错过了什么?

最佳答案

当然,这个问题是我在这个请求中使用了 JSONP,它不包括在发出请求时制作 header 的能力。见 how to change the headers for angularjs $http.jsonp .

具体来说,JSONP 只包含一个 <script> DOM 底部的标签以加载跨域 javascript,因此由您的浏览器发送默认 header 。

关于AngularJS ngResource 不发送自定义 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23743961/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com