繁体   English   中英

请求标头中存在缓存时,Chrome 浏览器和 CORS 问题

[英]Chrome Browser and CORS issue when caching present in request headers

我不确定这里是否讨论过这个问题,但有些事情很奇怪。 我在 Windows 10 中运行此版本的 Chrome:版本 86.0.4240.198(官方构建)(64 位)

我有一个域,比如 p.com,它正在从 Google Cloud Storage 中获取一个 PDF 文件,其中包含 url,例如: https://storage.googleapis.com/bucket/aaa.pdf

谷歌云存储已经有 CORS 这样的设置:

[{"maxAgeSeconds": 3600, "method": ["GET", "HEAD", "OPTIONS"], "origin": ["*"], "responseHeader": ["Content-Type", "Access-Control-Allow-Origin", "X-Requested-With", "Date", "Range", "Vary", "Access-Control-Allow-Headers"]}]

当我在请求标头中不缓存的情况下进行提取时,它是成功的。 但是当我在这样的请求标头中启用缓存时:

fetch("https://storage.googleapis.com/bucket/aaa.pdf", {
  "headers": {
    "cache-control": "max-age=315360000",
    "expires": "Mon, 06 Dec 2021 06:39:19 GMT",
    "pragma": "cache"
  },

  "method": "GET",
});

它失败并出现此错误:

Access to fetch at 'https://storage.googleapis.com/bucket/aaa.pdf' from origin 'http://p.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

我的问题是,CORS 和缓存是二元选择吗? 两者任一? 我的意思是你不能两者兼得。 我想启用 CDN 和缓存,以便快速加载资源。

您的 CORS 配置必须明确 state 允许哪些请求标头(除了少数已被视为“安全”的标头)。 因此,您收到该错误是因为您添加了不允许的请求标头。 要解决此问题,您需要在responseHeader字段中包含所有允许的标头。

也就是说,你确定你真的想要使用这些标题吗? 虽然可以使用Cache-Control作为请求 header,但它并不“启用缓存”。 您更有可能希望在response中设置这些标头,您可以通过配置Google Cloud Storage 来做到这一点。

在我自己摆弄了很多之后,我还观察到缓存的请求在 Chrome 中不包含Origin header,所以我不得不禁用缓存以避免 CORS 问题。 我通过在我的请求配置中添加cache: 'no-store'来做到这一点:

fetch(url, {
  method: 'GET',
  mode: 'cors',
  cache: 'no-store', // for some reason Chrome's caching doesn't send Origin
})

FWIW,Safari 在我的测试中没有表现出这种行为。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM