简体   繁体   中英

AngularJS include API key in a get request

I am trying to get information from a fantasy data API using AngularJS. I am using $resource to perform my get request in my controller, but I haven't been able to figure out how to correctly include the API key. Do I need to include it as a header? Thanks.

nflApp.controller('mainController', ['$scope','$resource','$routeParams', function($scope, $resource, $routeParams) {

$scope.fantasyAPI = $resource("https://api.fantasydata.net/nfl/v2/JSON/DailyFantasyPlayers/2015-DEC-28", { callback: "JSON_CALLBACK" }, { get: { method: "JSONP"}});

console.log($scope.fantasyAPI);

}]);

Below is the http request info from the site. http请求信息

You should set a header with the API key, AngularJS will send them with every request in the following case:

 $http.defaults.headers.common["Ocp-Apim-Subscription-Key"] = key;

When adding '.common' you are telling angular to send this in every request so you do not need to add it to every resource that hits the API.

A easy way to do that is by creating your own interceptors from $httpProvider at "config" fase.

To do that, just write something like:

mymodule.config(['$httpProvider', function($httpProvider){

$httpProvider.interceptors.push(function ($q) {
            return {
                'request': function (config) {
                    config.headers['Ocp-Apim-Subscription-Key'] = SomeUserClass.AuthToken();

                    return config;
                },

                'response': function (response) {



                    return response;
                }
            };
        });

});

You need to modify request header in JSONP. Unfortunately it is not possible. As the browser is responsible for header creation and you just can't manipulate that when using JSONP method.

how to change the headers for angularjs $http.jsonp

Set Headers with jQuery.ajax and JSONP?

From that link - https://johnnywey.wordpress.com/2012/05/20/jsonp-how-does-it-work/

Why NOT To Use JSONP?
Deciding against using JSONP is directly related to how it works. First of all, the only HTTP method you can use is GET since that is the only method script tags support. This immediately eliminates the use of JSONP as an option to interact with nice RESTful APIs that use other HTTP verbs to do fun stuff like CRUD. And while we're on the subject of GET, note that using anything other than URL parameters to communicate with the server API (eg sending some JSON over) is also not possible. (You could encode JSON as a URL parameter, but shame on you for even thinking that.)

If they only work with header manipulation you will need to do that call from your server side.

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