Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download Image using Fetch API

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?

like image 923
Tavish Aggarwal Avatar asked Oct 09 '17 08:10

Tavish Aggarwal


1 Answers

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

like image 161
ekanna Avatar answered Oct 22 '22 10:10

ekanna