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.

2
  • What authorisation scheme is using theapiurl.com? Commented Nov 1, 2013 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. mashape.com/docs/consume/rest#authorization Commented Nov 1, 2013 at 23:56

2 Answers 2

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';
Sign up to request clarification or add additional context in comments.

2 Comments

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

2 Comments

You don't need interceptors just to set default headers. there is an $httpProvider.defaults.header property just for that purpose.
This is a better approach if you're using third-party resources as well since you can define conditions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.