响应为404如何使用Service Worker缓存跨域资源?

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

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.

我已经将 CORS header 设置为:

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

但我仍然收到 "opaque" 响应,我无法确保代码为 200。 如果我缓存这些不成功的响应,它会导致一些问题。

比如网络好友导致跨域资源404, 然后我缓存它,然后我将始终使用这个 404 缓存响应,即使是在 网络问题已更正。 same-origin资源没有这个问题。

很遗憾,无法检测到它。

出于安全原因,明确不允许:https://github.com/whatwg/fetch/issues/14

一个Requestmode(据说)defaults to "no-cors"。 (我说 "allegedly" 是因为我相信我已经看到在 fetch() 中使用隐式创建的 Request 会导致启用 CORS 的 Response。)

因此,如果您知道您的服务器支持 CORS,则应该明确选择加入:

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

给定正确配置的远程服务器,启用 CORS 的 Request 将导致具有 type of "cors"Response。与 "opaque" Response 不同,"cors" Response 将暴露底层 statusbody