Download Image using Fetch API

橙三吉。 提交于 2020-01-13 10:53:31

问题


I know this question is answered, but I am facing issue while downloading image using Fetch API.
Code that I am using to get image.

function downloadImage() {
  fetch('https://upload.wikimedia.org/wikipedia/commons/9/98/Pet_dog_fetching_sticks_in_Wales-3April2010.jpg',
    {mode: 'no-cors'})
  .then(response => response.blob())
  .then(blob => {
        console.log(blob);           
  });
}

Here, when I do console.log I get response Blob {size: 0, type: ""}.
Please let me know what I am doing wrong here?


回答1:


By default fetch uses CORS mode. But when server response doesn't contain 'Access-Control-Allow-Origin' header. It skips response body.

Ironically, you have to set mode as 'no-cors' to request opaque resources. Opaque responses can't be accessed with JavaScript but the response can still be served or cached by a service worker.

https://developers.google.com/web/ilt/pwa/working-with-the-fetch-api



来源:https://stackoverflow.com/questions/46641508/download-image-using-fetch-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!