AngularJS在get请求中包含API密钥

Jef*_*ick 6 javascript angularjs

我正在尝试使用AngularJS从幻想数据API获取信息.我使用$ resource在我的控制器中执行我的get请求,但是我无法弄清楚如何正确地包含API密钥.我是否需要将其作为标题包含在内?谢谢.

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

}]);
Run Code Online (Sandbox Code Playgroud)

以下是该站点的http请求信息. http请求信息

FRE*_*CIA 1

您应该使用 API 密钥设置标头,在以下情况下,AngularJS 将随每个请求发送它们:

 $http.defaults.headers.common["Ocp-Apim-Subscription-Key"] = key;
Run Code Online (Sandbox Code Playgroud)

添加“.common”时,您是在告诉 Angular 在每个请求中发送此内容,这样您就不需要将其添加到访问 API 的每个资源中。