0

I want to send an api key for every request I make:

function MyService($http) {
    var req = {
        method: 'GET',
        url: 'https://api.giphy.com/v1/stickers/trending',
        headers: {
            'api_key':'123' 
        }
    }

    return $http(req);
}

but the problem is that all requests are OPTIONS (not GET) and is not sending the api_key. Is that the right way to send headers? thanks

Editing because it was marked as duplicate:
This is not a CORS issue. The error I´m getting is 401. That means authentication failed because the endpoint is not receiving the request header with the api_key.

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
handsome
  • 2,335
  • 7
  • 45
  • 73
  • what do you mean with "all requests are OPTIONS (not GET) "? check the network tab on the google console and see if there's something wrong there... – Paolo Aug 12 '17 at 19:28
  • The OPTIONS request is a CORS pre-flight request. – georgeawg Aug 12 '17 at 21:17

1 Answers1

0

What you did is totally fine, but if the api_key is always different, so you have to provide the api_key value dynamically in order to be added to the request.

If it is always the same, you have a really better way to do that: through interceptors. And you will set that only one time. Again, this method is if you have to set up some parameter which is always the same, so actually it is for doing standard operations over HTTP requests.

First, you need to define your Interceptor:

myApp.service('MyRequestsInterceptor', [function() {
    this.request = function(config) {
        config.headers.api_key = 'My Default API KEY';
        return config;
    };
}]);

And then simply add your interceptor to AngularJS $httpProvided:

myApp.config([ '$httpProvider',   function($httpProvider) {
    $httpProvider.interceptors.push('MyRequestsInterceptor');
} ]);
quirimmo
  • 9,800
  • 3
  • 30
  • 45
  • actually the API key is always the same. this work just fine if I make a request to that endpoint and send the api_key as a querystring. according to the documentation both methods are valid – handsome Aug 12 '17 at 22:49