how to use Service Worker to cache cross domain resources if the response is 404?

12,764

The mode of a Request (allegedly) defaults to "no-cors". (I say "allegedly" because I believe I've seen situations in which an implicitly created Request used in fetch() results in a CORS-enabled Response.)

So you should be explicit about opting in to CORS if you know that your server supports it:

var corsRequest = new Request(url, {mode: 'cors'});
fetch(corsRequest).then(response => ...); // response won't be opaque.

Given a properly configured remote server, a CORS-enabled Request will result in a Response that has a type of "cors". Unlike an "opaque" Response, a "cors" Response will expose the underlying status, body, etc.

Share:
12,764
abu
Author by

abu

Updated on July 19, 2022

Comments

  • abu
    abu almost 2 years

    w3:

    6.2 Cross-Origin Resources and CORS¶
    Applications tend to cache items that come from a CDN or other origin. It is possible to request many of them directly using <script>, <img>, <video> and <link> elements. It would be hugely limiting if this sort of runtime collaboration broke when offline. Similarly, it is possible to XHR many sorts of off-origin resources when appropriate CORS headers are set.

    ServiceWorkers enable this by allowing Caches to fetch and cache off-origin items. Some restrictions apply, however. First, unlike same-origin resources which are managed in the Cache as Response objects with the type attribute set to "basic", the objects stored are Response objects with the type attribute set to "opaque". Responses typed "opaque" provide a much less expressive API than Responses typed "basic"; the bodies and headers cannot be read or set, nor many of the other aspects of their content inspected. They can be passed to event.respondWith(r) method in the same manner as the Responses typed "basic", but cannot be meaningfully created programmatically. These limitations are necessary to preserve the security invariants of the platform. Allowing Caches to store them allows applications to avoid re-architecting in most cases.

    I have set the CORS header like:

    Access-Control-Allow-Origin:https://xxx.xx.x.com
    Access-Control-Allow-Credentials:true
    

    but I still get an "opaque" response and I cannot ensure the code is 200. If I cache these unsuccessful responses, it will cause some problem.

    For example, a chum of network causes a 404 to the cross domain resources, and I cache it, then I will always use this 404 cache response even thongth when the network problem is corrected. The same-origin resource do not have this problem.

  • abu
    abu about 8 years
    waoooooooooooooo~~~~ Thank you very very much!!! It is really working for me. mua~~
  • Anne
    Anne about 8 years
    The question here is how you originally make the requests that are you tunneling through the service worker. If those use "no-cors", that's what you'll get. new Request("x").mode returns "cors" though.