2014-05-19 182 views
4

我正在嘗試使用ngResource來查詢REST API。我需要在自定義標題中指定我的API密鑰。我已經試過了,像這樣:AngularJS ngResource不發送自定義標頭

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

    }; 

    }]); 

然後我在我的控制器使用這樣的:當我檢查XHR

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

我的自定義標題沒有設置。另外,爲什麼在最初的$resource:get()方法之後我呼叫空的.get()之前,XHR不會運行?

我也試圖設置標題中$httpResource直接:

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

,但是這仍然沒有設置自定義標題,當我檢查網絡請求。我錯過了什麼?

+0

您使用JSONP作爲方法。 – zeroflagL

+0

可能重複[如何更改angularjs $ http.jsonp的標頭](http://stackoverflow.com/questions/19603757/how-to-change-the-headers-for-angularjs-http-jsonp) – maxdec

+1

@ maxdec我認爲你是對的。由於無論出於何種原因,在過去的24小時內都得到了一點關注,所以我會將其作爲答案並進行交流。 –

回答

0

這個問題當然是我在這個請求中使用了JSONP,它不包括在發出請求時創建頭部的能力。見how to change the headers for angularjs $http.jsonp

具體來說,JSONP只是在DOM的底部包含一個<script>標記以加載跨域javascript,所以發送默認標題由您的瀏覽器決定。