简体   繁体   中英

Chrome Browser and CORS issue when caching present in request headers

I am not sure if this problem has been discussed here, but something is strange. I am running this version of Chrome in Windows 10: Version 86.0.4240.198 (Official Build) (64-bit)

I have a domain, say p.com, it is fetching a PDF file from the Google Cloud Storage, with url such as this: https://storage.googleapis.com/bucket/aaa.pdf

The Google Cloud Storage already has CORS setup as such:

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

When I do a fetch without caching in the request headers, it is successful. But when I enable caching in the request headers such as this:

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",
});

It fails with this error:

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.

My question is, is CORS and caching a binary choice? Either or? I mean you cannot have both. I would like to enable CDN and caching so that the resource is loaded quickly.

Your CORS configuration must explicitly state what request headers are allowed (other than a small number of headers already considered "safe"). So you're getting that error because you added request headers that aren't allowed. To fix that you need to include all allowed headers in the responseHeader field.

That said, are you sure you actually want to use those headers? While it's possible to use Cache-Control as a request header, it's unusual and doesn't "enable caching". More likely you want those headers to be set in the response , which you can do by configuring Google Cloud Storage.

After fiddling with this quite a bit myself, I also observed that cached requests do not contain the Origin header in Chrome, so I had to disable caching to avoid CORS issues. I did this by adding cache: 'no-store' to my request config:

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

FWIW, Safari did not exhibit this behavior in my tests.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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