javascript - 如何使用我的 Service Worker 处理由 AWS s3 产生的非 CORS 污染的浏览器缓存?

标签 javascript amazon-s3 cors service-worker

我的公司有许多应用程序请求位于 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.comhttps://cors-test.appspot.com/test 发出启用 CORS 的请求。第一个请求将失败,因为服务器不支持 CORS,而第二个请求将成功并使用非不透明的 Response 对象进行解析。

关于javascript - 如何使用我的 Service Worker 处理由 AWS s3 产生的非 CORS 污染的浏览器缓存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41132482/

相关文章:

javascript - 处理多次调用 AngularJS promise 中的错误

javascript - 如何在任务中使用单个单击处理程序而不是多个单击处理程序?

javascript - jQuery 验证器 addMethod,无论显示什么错误消息

node.js - AWS CodeBuild 永远转移到 S3 步骤

javascript - 为什么对象解构不起作用?

javascript - SailsJS Captain-s3 文档建议 S3 存储桶应采用美国标准 - 但 S3 UI 中没有这样的区域

Coldfusion Amazon S3 支持文件上传,它是否连接到特定 IP?

javascript - Vanilla JS : No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' 因此不允许访问

safari - Safari 是否支持 Access-Control-Expose-Headers header ?

javascript - 从文件 ://scheme 运行的应用程序的 CORS 错误