我一直在尝试使用$http.jsonp从我的AngularJS代码中调用外部API (Vimeo)。但我得到的只是一个401授权要求,即使我把我的授权密钥加到了头上。用jQuery.ajax()做同样的事情也有类似的问题。但在jQuery中,我通过设置beforeSend函数来解决这个问题,该函数使用xhr对象在请求头上设置授权密钥。
我的代码:
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一样
发布于 2014-09-29 02:39:50
在angular中,你可以使用http interceptor
Ng.module(‘拦截器’) .factory('authorizationInterceptor',function () { return { request: function (config) { config.headers = config.headers || {};config.headers.Authorization =‘承载’+ '34210aeac4e02a251b8821a53620e93c';return config;}};});
httpProvider(‘$httpProvider.interceptors.push('authorizationInterceptor');$httpProvider.defaults.headers.common"X-Requested-With“’,[])angular.module([‘$httpProvider’,.config ($httpProvider) {myApp‘,[]).config(’myApp‘,[]).config(['$httpProvider',$httpProvider){myApp= 'XMLHttpRequest';}]);
注意,我认为无记名的第一个字母必须是大写的。
发布于 2014-09-29 14:20:48
我不太了解Angular,但我认为问题在于您使用的是JSONP。因为它使用浏览器的script标签来绕过CORS限制,所以它不允许除get或setting标头之外的谓词。
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);
});
};
https://stackoverflow.com/questions/26087665
复制