简体   繁体   中英

sending API key in the request headers with angularJS 1.6.3

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 .

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'); } ]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM