2014-09-28 29 views
0

我一直在嘗試從我的AngularJS代碼調用外部API(Vimeo),使用$ http.jsonp。但我得到的是一個401所需的授權,即使我將我的授權密鑰添加到標題。在jQuery.ajax()方面也有類似的問題。但與jQuery我解決了這個問題,通過設置beforeSend函數來設置我的授權密鑰在請求頭使用xhr對象。Vimeo API請求與AngularJs「401需要授權」

我的代碼:

function(){ 
 
    var config = { 
 
       headers: {Authorization: "bearer 34210aeac4e02a251b8821a53620e93c"}, 
 
       params : { 
 
        callback: 'JSON_CALLBACK' 
 
        } 
 
       }; 
 
    var url = "https://api.vimeo.com/tags/fun/videos?per_page=5"; 
 
    $http.jsonp(url, config).success(function(response){ 
 
     console.log(response); 
 
    }); 
 
};

我怎麼得到這個工作。是某種config.beforeSend的,我可以用它來設置頁眉就像jQuery的

回答

0

在角可以使用http interceptor

  1. 定義你的HTTP攔截器:這一塊將增加在每個HTTP令牌要求

    ng.module('interceptors') 
    .factory('authorizationInterceptor', function() { 
        return { 
         request: function (config) { 
          config.headers = config.headers || {}; 
          config.headers.Authorization = 'Bearer ' + '34210aeac4e02a251b8821a53620e93c'; 
          return config; 
         } 
    };}); 
    
  2. 註冊攔截

    angular.module('myApp',[]).config(['$httpProvider',function ($httpProvider) { 
        $httpProvider.interceptors.push('authorizationInterceptor'); 
        $httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest'; 
    }]); 
    

注意,我想承載的第一個字母必須大寫字母在你頭

0

不知角度太清楚,但我認爲問題是,你正在使用JSONP。由於它使用瀏覽器的腳本標籤來解決CORS限制,因此它不允許使用GET以外的其他動詞,也不允許設置標題。

Vimeo API支持CORS頭文件,因此您實際上想要使用瀏覽器的AJAX功能進行常規GET請求。我相信AngularJS提供了$http.get函數來完成你目前正在做的事(docs)。

我會嘗試:

function(){ 
    var config = { 
     headers: {Authorization: "Bearer 34210aeac4e02a251b8821a53620e93c"} 
    }; 
    var url = "https://api.vimeo.com/tags/fun/videos?per_page=5"; 
    $http.get(url, config).success(function(response){ 
     console.log(response); 
    }); 
}; 
相關問題