Google Cloud Storage 忽略访问控制来源 headers

Google Cloud Storage ignoring access control origin headers

我正在尝试通过 AJAX 从本地主机上的 google 云存储中获取文件。我做了以下事情:

通过 gsutil 为我的存储桶设置 CORS:

gsutil cors set cors.json gs://my-project

cors.json 文件所在的位置:

[
  {
    "origin": [
      "*"
    ],
    "responseHeader": ["Origin", "Accept", "X-Requested-With", "Authorization", "Content-Type",     "Content-Length", "Accept-Encoding", "X-CSRF-Token"],
    "method": [
      "GET",
      "OPTIONS"
    ],
    "maxAgeSeconds": 1
  }
]

我已经用gsutil cors get gs://my-project

验证过了

然后我为每个文件制作了 public,上传文件时都通过 node.js 客户端库:

bucket.file(object.name).makePublic()

通过控制台和 gsutil:

gsutil -m acl set -R -a public-read gs://my-project

然后在我的ajax请求中,我也发送headers:

$.ajax({
            method: "GET",
            url: "https://googleapis.com/storage/v1/b/my-project/o?delimiter=audio",
            headers: {
                'Access-Control-Allow-Origin': '*'
            },
            crossDomain: true,
        }).done((data) => {
            console.log(data)
        })

我仍然收到 cors 错误:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

我如何通过 CORS?

您使用的是 "googleapis.com" 而不是 "www.googleapis.com"。添加 "www",您的代码将起作用。

您似乎没有进行任何身份验证,因此您还需要确保您的存储桶允许匿名用户列出对象(gsutil acl ch -g allUsers:R gs://bucket-name 将进行设置)。

接下来,对于匿名请求,最好添加一个 API 关键参数,将请求与您的 Google 云项目相关联。 GCS 将允许完全匿名的请求,但如果请求过于频繁,它们可能会被阻止。

最后,只有 XML API 遵守存储桶上的 CORS 策略。 JSON API,即端点为 "www.googleapis.com" 的那个,将愉快地响应跨源请求,而无需在存储桶上设置任何特殊属性。