问题描述
我在 Google Cloud Storage 中存储了一个公开可用的文件,并且在使用 fetch 从 SPA 检索资源时遇到问题。假设存储桶名称为 pub-bucket
,完整资源 URL 为 https://storage.googleapis.com/pub-bucket/v1/example.mid
。我已经使用以下 JSON 配置为存储桶启用了 CORS
[
{
"origin": ["*"],"method": ["GET"]
}
]
但我仍然收到相同的 CORS 错误 Access to fetch at 'https://storage.googleapis.com/pub-bucket/v1/example.mid' from origin 'http://localhost:3001' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
我不确定是否配置错误,因为我以前使用具有相同 CORS 配置的 DO Spaces 并且从未见过此问题。我还尝试使用 this 回答中提到的更多选项扩展我的 CORS 配置,但没有任何改变。
解决方法
事实证明,这个问题是由于 Google 没有明确定义可以使用 CORS 访问哪些端点。资源 https://storage.googleapis.com/[YOUR-BUCKET]/[OBJECT-PATH]
的此 URI 版本不允许 CORS 访问,而 https://[YOUR-BUCKET].storage.googleapis.com/[OBJECT-PATH]
允许。