0

I'm trying to learn AngularJS. I'm try to make a simple authenticated get request to a REST api. At this point, i'm just trying to get a response back. I keep getting invalid key because I can't seem to send the headers properly.

angular.module('App', ['ngResource']);

function AppCtrl($scope, $resource){
$scope.app = $resource('https://theapiurl.com/parameter=:action',
    {action:'My Parameter works fine!'}, 
    {method: 'GET'},
    {headers: 'auth-key' : 'key'});
$scope.app.get();
}

I just can't seem to get the header to send. Thanks for reading.

WordPress Mike
  • 448
  • 2
  • 6
  • 21
  • What authorisation scheme is using `theapiurl.com`? – ssedano Nov 01 '13 at 23:46
  • Im really not sure how to answer that. The api and key are provided by mashape.com. This doc describes how they authenticate. https://www.mashape.com/docs/consume/rest#authorization – WordPress Mike Nov 01 '13 at 23:56

2 Answers2

4

If you are using angular-resource 1.1.x+ the following should work:

angular.module('App', ['ngResource']);

function AppCtrl($scope, $resource){
    $scope.app = $resource('https://theapiurl.com/parameter=:action',
      {
        action:'My Parameter works fine!'
      }, 
      {
        get: {
          method: 'GET',
          headers : { 'auth-key' : 'key' }
        }
      });
     $scope.app.get();
}

If you are using 1.0.x branch this won't work. I believe the only alternative is to set global default headers in $httpProvider, or to user $http directly (not using $resource). Here's how you would set the headers globally:

$httpProvider.defaults.headers.get['auth-key'] = 'key';
Daniel Tabuenca
  • 13,147
  • 3
  • 35
  • 38
  • I had missed one thing in my answer. I updated it to show the correct way. Note this will only work in 1.1.x and above. – Daniel Tabuenca Nov 02 '13 at 04:56
  • Excellent. I switched to version 1.1.5 from 1.0.7 and added the `get` action and it works as intended! Though, You have an extra curly brace I believe. Thanks so much for your help. – WordPress Mike Nov 02 '13 at 05:28
1

To avoid setting the header in every resource you could use an interceptor:

app.config(function($httpProvider) {
    $httpProvider.interceptors.push(function($q) {
        return {
            'request': function(config) {
            config.headers['auth-key'] = 'key';
                return $q.when(config);
            }
        };
    });
});
Steve Davis
  • 716
  • 5
  • 13
  • You don't need interceptors just to set default headers. there is an $httpProvider.defaults.header property just for that purpose. – Daniel Tabuenca Nov 02 '13 at 04:59
  • This is a better approach if you're using third-party resources as well since you can define conditions. – Fardin K. Dec 20 '14 at 20:34