Pregunta

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.

¿Fue útil?

Solución

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';

Otros consejos

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);
            }
        };
    });
});
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top