What is an opaque response, and what purpose does it serve?

Miguel Angelo picture Miguel Angelo · Mar 29, 2016 · Viewed 123.4k times · Source

I tried to fetch the URL of an old website, and an error happened:

Fetch API cannot load http://xyz.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://abc' is therefore not allowed access.
If an opaque response serves your needs, set the request's mode to 'no-cors'
to fetch the resource with CORS disabled.

I understood the message, and tried to do a request that returns an opaque response:

fetch("http://xyz", {'mode': 'no-cors'})

Ok, it now works... but I can't read it. =\

What's the purpose then, of an opaque response?

Answer

Salva picture Salva · Mar 30, 2016

Consider the case in which a service worker acts as an agnostic cache. Your only goal is serve the same resources that you would get from the network, but faster. Of course you can't ensure all the resources will be part of your origin (consider libraries served from CDNs, for instance). As the service worker has the potential of altering network responses, you need to guarantee you are not interested in the contents of the response, nor on its headers, nor even on the result. You're only interested on the response as a black box to possibly cache it and serve it faster.

This is what { mode: 'no-cors' } was made for.