如何使用获取获取网站图标并避免CORS策略阻止请求

时间:2018-11-06 13:11:57

标签: javascript cors fetch-api

我创建了以下javascript代码以获取ebay.com网站的收藏夹图标。不幸的是,由于CORS政策,请求失败。如果将模式设置为“ no-cors”,则会收到0状态代码和“不透明”响应,因此我不知道请求是否成功以及如何处理响应!

如何解决使用提取的CORS策略阻止问题?

let headers = new Headers();
let init = { 
  method: 'GET',
  headers: headers,
  mode: 'cors',
  responseType: 'arraybuffer' 
};
let req = new Request("https://ebay.com/favicon.ico", init);
fetch(req)
    .then(
      function(response) {
        if (response.ok) {
        	console.log(response.arrayBuffer());
          return response.arrayBuffer();
        }
          console.log("Looks like there was a problem. Status Code: " + response.status);
          throw new Error('Network response was not ok.');
      }
  )
    .then(
      function(arrayBuffer){
        let encoding = "utf-16";
        let dataView = new DataView(arrayBuffer);
        let decoder = new TextDecoder(encoding);
        let decodedString = decoder.decode(dataView);
        let base64String = btoa(decodedString);
        console.log("Base64 string for favicon: " + base64String);
      }
  )
    .catch(
      function(err) {
        console.log('Fetch Error :-S', err);
      }
  );

0 个答案:

没有答案