4

I'm attempting to use ngResource to query a REST API. I need to specify my API key in a custom header. I've tried it like so:

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

    };

  }]);

which I then use in my controller like:

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

My custom header isn't set when I inspect the XHR. Also, why will the XHR not run until I call an empty .get() after the initial $resource:get() method?

I've also tried to set the headers in $httpResource directly:

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

but this still doesn't set the custom header when I inspect the network request. What am I missing?

Charlie Schliesser
  • 7,851
  • 4
  • 46
  • 76
  • You use JSONP as method. – a better oliver May 19 '14 at 21:53
  • possible duplicate of [how to change the headers for angularjs $http.jsonp](http://stackoverflow.com/questions/19603757/how-to-change-the-headers-for-angularjs-http-jsonp) – maxdec Oct 17 '14 at 15:24
  • 1
    @maxdec I think you're right. Since this for whatever reason has gotten a little bit of attention in the past 24 hours, I'll post that as the answer and crosslink. – Charlie Schliesser Oct 17 '14 at 15:27

1 Answers1

0

This issue is, of course, that I was using JSONP in this request, which doesn't include the ability to craft headers when making a request. See how to change the headers for angularjs $http.jsonp.

Specifically, JSONP simply includes a <script> tag at the bottom of the DOM to load cross-domain javascript, so it's up to your browser to send the default headers.

Community
  • 1
  • 1
Charlie Schliesser
  • 7,851
  • 4
  • 46
  • 76