首页 > 解决方案 > 如何使用 Google Cloud Storage 在 CORS json 文件中设置多个来源?

问题描述

我正在尝试将多个 CORS 源站点与 Google Storage 一起使用。

Mozilla Firefox 似乎没有任何多源问题。但是谷歌浏览器会抛出这个错误:Access to XMLHttpRequest at 'FILE AT GOOGLE STORAGE' from origin 'https://example2.org' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header has a value 'https://example1.org' that is not equal to the supplied origin.

我试过像这样编写cors json文件:

[
    {
      "origin": ["https://example1.org", "https://example2.org"],
      "responseHeader": ["Content-Type"],
      "method": ["GET", "HEAD"],
      "maxAgeSeconds": 1800
    } 
]

就像这样:

[
    {
      "origin": ["https://example1.org"],
      "responseHeader": ["Content-Type"],
      "method": ["GET", "HEAD"],
      "maxAgeSeconds": 1800
    },
    {
      "origin": ["https://example2.org"],
      "responseHeader": ["Content-Type"],
      "method": ["GET", "HEAD"],
      "maxAgeSeconds": 1800
    }  
]

谷歌浏览器不喜欢这两种变体。

标签: google-cloud-platformcors

解决方案


您指定的第一种方式是正确的,保存一个 JSON 文件(即。bucket-cors-config.json):

[{
  "origin": ["https://example1.org", "https://example2.org"],
  "responseHeader": ["Content-Type"],
  "method": ["GET", "HEAD"],
  "maxAgeSeconds": 1800
}]

然后使用gcloudcli util 在您的存储桶上进行设置:

gsutil cors set bucket-cors-config.json gs://my-bucket

如果您在浏览器中检查不同的来源并且收到 CORS 错误,请确保这不是因为浏览器缓存。由于目标 URL 匹配,某些浏览器会在错误的来源上使用缓存的响应。此缓存响应将具有错误的原始标头并导致 CORS 错误。


推荐阅读