我的公司有许多应用程序请求位于 AWS S3 上的共享资源。其中一些应用程序使用 crossorigin="anonymous" html 元素,有些则没有。 AWS 不会发回 CORS 响应 header ,例如“Allow-access-control-origin”when there is no Origin request header 。因此,某些用户最终可能会得到没有 CORS 响应 header 的文件的浏览器缓存版本。
当这些用户访问我团队的应用程序时,Service Worker 可能无法请求这些共享资源,因为浏览器磁盘缓存以非 cors 方式保存它们。错误看起来像这样:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8001' 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.
当然,我不能使用不透明的响应来实现可靠的缓存。
我想我可以应用缓存控制请求 header 来绕过浏览器缓存,但是 Fetch API Request is immutable 的 Headers 对象。因此,我无法向现有请求添加 header 。如果我尝试发出新请求,我无法从 AWS 获得 CORS 响应,因为 Origin is a forbidden header我无法在 Fetch API 中设置。
如果满足以下条件,此问题将得到解决:
我可以强制公司中的所有团队确保他们使用 crossorigin html 属性,但我不能。
我可以让 AWS 始终使用 CORS header 进行响应,但我不能。
使用 Origin header 发出获取请求,但我不能。
说服我的组织设置缓存控制 header ,禁止浏览器缓存资源,但这是一个坏主意。
我能做些什么来克服这个问题吗?现在,我只是禁用这些共享 Assets 上的 Service Worker 缓存,以避免网络故障。
最佳答案
您说如果您可以使用 Origin header 发出 Fetch 请求,您的问题就会得到解决,但我不能。
您应该能够通过构造自己的 Request
并显式设置 mode
来做到这一点。到'cors'
。这是一个例子:
const failingRequest = new Request('https://example.com', {
mode: 'cors'
});
fetch(failingRequest).then(console.log).catch(console.warn);
const successfulRequest = new Request('https://cors-test.appspot.com/test', {
mode: 'cors'
});
fetch(successfulRequest).then(console.log).catch(console.warn);
您应该看到向 https://example.com
和 https://cors-test.appspot.com/test
发出启用 CORS 的请求。第一个请求将失败,因为服务器不支持 CORS,而第二个请求将成功并使用非不透明的 Response
对象进行解析。
关于javascript - 如何使用我的 Service Worker 处理由 AWS s3 产生的非 CORS 污染的浏览器缓存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41132482/