You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google Cloud存储文件下载CORS问题排查与解决求助

解决Google Cloud存储桶CORS下载问题

问题描述

请求下载存储桶文件时触发CORS错误:

Access to XMLHttpRequest at 'https://storage.googleapis.com//myimage.png' from origin 'http://localhost:3000' 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.

已执行操作

  • 通过gcloud CLI配置CORS:
    gcloud storage buckets update gs://<MY-BUCKET-NAME> --cors-file=cors.json
    
  • 使用的cors.json内容:
    [    
      {      
        "origin": ["*"],      
        "method": ["*"],      
        "responseHeader": ["Content-Type"],      
        "maxAgeSeconds": 3600    
      }
    ]
    
  • 验证配置命令及结果:
    gcloud storage buckets describe gs://<MY-BUCKET-NAME> --format="default(cors)"
    
    响应:
    cors:
    - maxAgeSeconds: 3600
      method:
      - '*'
      origin:
      - '*'
      responseHeader:
      - Content-Type
    
  • 云控制台无CORS配置标签,前端下载函数代码:
    const download = () => {
      // props.url = https://storage.googleapis.com/${bucket.name}/${blob.name}
      const url = `${props.url}`;
    
      const headers = {
        Authorization: "Bearer " + process.env.REACT_APP_STORAGE_TOKEN,
        "Access-Control-Allow-Origin": "http://localhost:3000",
      };
      axios({
        method: "GET",
        headers,
        url,
        responseType: "blob",
      })
        .then((response) => {
          setIsDownloading(false);
          const href = URL.createObjectURL(response.data);
          var link = document.createElement("a");
          link.href = href;
          link.setAttribute(
            "download",
            replace("%", " ", props.name.split("?")[0])
          );
          link.click();
          URL.revokeObjectURL(href);
        })
        .then((data) => {});
    };
    

解决方案

1. 移除前端请求中的无效头

Access-Control-Allow-Origin是服务器返回给浏览器的响应头,不需要在前端请求中设置,删除该字段:

const headers = {
  Authorization: "Bearer " + process.env.REACT_APP_STORAGE_TOKEN,
  // 移除 "Access-Control-Allow-Origin": "http://localhost:3000"
};

2. 更新CORS配置以支持授权头

请求中包含Authorization头,需要将其加入CORS允许的响应头列表,更新cors.json:

[    
  {      
    "origin": ["*"],      
    "method": ["*"],      
    "responseHeader": ["Content-Type", "Authorization"],      
    "maxAgeSeconds": 3600    
  }
]

重新执行配置更新命令:

gcloud storage buckets update gs://<MY-BUCKET-NAME> --cors-file=cors.json

3. 等待配置生效并清除缓存

CORS配置可能需要数分钟全局生效,尤其是多区域存储桶。等待后清除浏览器缓存再测试。

4. 验证令牌权限

确保REACT_APP_STORAGE_TOKEN对应的账号拥有目标对象的storage.objects.get权限,可通过以下命令检查:

gcloud storage objects get-iam-policy gs://<MY-BUCKET-NAME>/myimage.png

5. 简化测试(可选)

临时将对象设置为公开可读(测试后恢复权限),用不带授权头的请求测试CORS是否正常。若公开访问时CORS生效,说明问题出在授权头配置或令牌权限上。

内容的提问来源于stack exchange,提问作者Ayabonga Qwabi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 09:07:24