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

w3:

6.2 Cross-origin and CORS resources ¶
        Applications tend to cache items that come from a CDN or other source. You can request many of them directly using <script>, <img>, <video>and <link>. This would be extremely restrictive if such a runtime environment was disconnected offline. Similarly, it is possible for XHR to have many different resources outside of origin when the corresponding CORS headers are set.

ServiceWorkers resolves this by allowing caches to cache and cache Items. However, there are some limitations. First, unlike single-source resources that are managed in Cache as Response objects with a set of type attributes to "primary", stored objects are Response objects with a set of type attributes to "opaque". Answers printed by “opaque” provide a much less expressive API than Answers typed by “core”; bodies and headings cannot be read or set, nor many about other aspects of their content. They can be passed to event.respondWith (r) in the same way that Answers typed “basic,” but cannot be meaningfully created programmatically. These restrictions are necessary to preserve platform security invariants.Allowing caches to store them allows applications to avoid re-archiving in most cases.

I set the CORS header, for example:

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

but I still get an “opaque” response, and I can’t provide 200 code. If I cache these unsuccessful answers, this will cause some problems.

For example, a network buddy calls 404 for cross-domain resources, and I cache it, then I will always use this 404 cache response even when the network problem is fixed. A resource of the same source does not have this problem.

+4
source share
2 answers

mode Request(presumably) by default"no-cors" . (I claim that I assumed that I saw situations in which implicitly created Request, used in fetch(), results in CSR-enabled Response.)

, , CORS, , :

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

, Request CORS Response, type of "cors". "opaque" Response, "cors" Response status, body ..

+3

All Articles