【问题标题】:AngularJS ngResource not sending custom headerAngularJS ngResource 不发送自定义标头
【发布时间】:2014-07-07 18:43:29
【问题描述】:

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

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

    };

  }]);

然后我在我的控制器中使用它:

app.controller('MyCtrl', function ($scope, Api, ENV) {
  Api.init(ENV.apiEndpoint, ENV.apiKey);
  var widgets = Api.get('widgets');
});

当我检查 XHR 时,我的自定义标题没有设置。另外,为什么 XHR 不会运行,直到我在初始 $resource:get() 方法之后调用一个空的 .get()

我也尝试直接在$httpResource 中设置标题:

  .config(function($httpProvider) {
    $httpProvider.defaults.headers.get  = {'api_key': 'abc123'};
  })

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

【问题讨论】:

  • 你使用 JSONP 作为方法。
  • @maxdec 我认为你是对的。由于这在过去 24 小时内无论出于何种原因引起了一些关注,我将把它作为答案和交叉链接发布。

标签: angularjs ngresource


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2015-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-26
    相关资源
    最近更新 更多