23

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?

12
  • 2
    You should use {mode: 'cors'}. Commented Oct 9, 2017 at 8:20
  • With it I am getting error: No 'Access-Control-Allow-Origin' header is present on the requested resource.If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. Commented Oct 9, 2017 at 8:25
  • 1
    @TavishAggarwal Are you fetching wikimedia images ? Because they definitely have CORS headers and this code will definitely work. If you want to fetch some other 3rd party resources, then it's not possible without those headers. Commented Oct 9, 2017 at 8:31
  • 1
    Yes, @BrahmaDev.. I am fetching third party images with mode {mode: 'no-cors'}. But am getting empty object. Commented Oct 9, 2017 at 8:33
  • 1
    @Kaiido - perhaps I did Commented Oct 15, 2017 at 5:52

1 Answer 1

15

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

Sign up to request clarification or add additional context in comments.

1 Comment

Could you explain, how to use "service workers"? I use raw JS and fetch API, in browser console I see server responses with image, but JS promise does not have Body (null) and status = 0 (?!)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.