2017-07-18 163 views
0

我採用了棱角分明JS得到使用Authorization: Bearer令牌服務器的圖像從服務器獲取影像。我已經通過Loading Image in JavaScript with Bearer token的例子。如何使用授權令牌承載角使用JS

我已經使用了類似的代碼,

var request = new XMLHttpRequest(); 
request.open('GET','https://dl.content.com/contentfile.jpg', true); 
request.setRequestHeader('Authorization', 'Bearer ' + oauthToken.access_token); 
request.responseType = 'arraybuffer'; 
request.onload = function(e) { 
    var data = new Uint8Array(this.response); 
    var raw = String.fromCharCode.apply(null, data); 
    var base64 = btoa(raw); 
    var src = "data:image;base64," + base64; 

    document.getElementById("image").src = src; 
}; 

request.send(); 

它工作正常。但它是用普通的JavaScript編寫的。我只是想知道是否有任何使用Angular JS實現相同的東西的等價語法?

我一直在使用Angualar JS的$http去做嘗試。我的代碼如下,

$http({ 
      method: 'GET', 
      url: file, 
      headers: { 
       'Authorization': 'Bearer ' + Constants.token 
      } 
     }).then(function (data) { 
      console.log('from backend', data) 
     }) 

但它給出了以下錯誤和瀏覽器被絞死。

錯誤截圖 Error Screenshot

我不知道爲什麼發生錯誤,以及如何解決它。

回答

0

我通常做的是使用攔截器對於我提出的要求。

$httpProvider.interceptors.push('myInterceptor'); 

並使用工廠來處理請求和響應。

.... .factory('myInterceptor', function() { 
return { 
    request: function(config) { 
     config.headers.Authorization="Bearer "+ myberer 
     return config; 
    }, 
    requestError: function(reject) { 
     // do something on error 
     console.log('request Error') 
    }, 
    response: function(config) { 

    }, 
    responseError: function(reject) { 
    } 
}; 

你可以找到這篇文章 http://www.webdeveasy.com/interceptors-in-angularjs-and-useful-examples/

或搜索有關angularJs攔截更多的相關信息