【问题标题】:Google Cloud Storage Bucket CORS error although CORS policy set尽管设置了 CORS 政策,但 Google Cloud Storage Bucket CORS 错误
【发布时间】:2020-11-05 06:02:07
【问题描述】:

我有一个用于谷歌云存储桶的签名URL,我想将它与 axios 一起使用来发出 PUT 请求。

当变量 signedURL 不为空时,通过 useEffect 调用我的 putFileData 函数。

  const putFileData = async () => {
    await axios
    .put(signedURL, "HELLO TXT!!!!")
    .then((response) => console.log(response))
    .catch(err => {console.log("AXIOS ERROR: ", err)})  
}

我使用 json 文件在存储桶上设置了 CORS 策略,当我查询存储桶的 cors 策略时,我得到:

[{"maxAgeSeconds": 360, "method": ["PUT"], "origin": ["http://localhost:3000"], "responseHeader": ["Content-Type"]}]

我的签名网址上的选项是:

const options = {
  version: 'v4',
  action: 'write',
  expires: Date.now() + 15 * 60 * 1000, // 15 minutes
  contentType: 'application/octet-stream',
};

但我仍然无法从 http://localhost:3000 发出 PUT 请求。

我明白了:

Access to XMLHttpRequest at 'mysignedurl' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

和:

PUT mysignedurl::ERR_FAILED

在我的 Chrome 开发者工具的网络选项卡中,它显示请求已发出两次 - 第一次未成功,状态为 403,然后成功,状态为 200 - 但没有任何内容上传到存储桶。

我的签名网址是在我的 Cloud Functions 中使用此函数生成的:

async function generateV4UploadSignedUrl(bucketName, fileName) {
// These options will allow temporary uploading of the file with outgoing
// Content-Type: application/octet-stream header.
const options = {
  version: 'v4',
  action: 'write',
  expires: Date.now() + 15 * 60 * 1000, // 15 minutes
  contentType: 'application/octet-stream',
};

// Get a v4 signed URL for uploading file
const [url] = await storage
  .bucket(bucketName)
  .file(fileName)
  .getSignedUrl(options)
  
return url;

};

【问题讨论】:

  • 您能分享一下您是如何创建签名 URL 的吗?您能否将响应标头添加如下:“responseHeader”:[“Content-Type”,“access-control-allow-origin”]}] 并检查您是否仍然收到错误?
  • 我确实修改了 responseHeader 并添加了生成我的 signedUrl 的函数。
  • 我返回的signedUrl是一个以storage.googleapis.com/mybucket开头的,那是JSON Api上传,似乎不接受CORS,cloud.google.com/storage/docs/request-endpoints#xml-api,但这是signedURL函数返回的url?有没有办法生成 XML 签名 URL?
  • 我有完全相同的代码,但无论我尝试什么仍然会出现此错误:-/
  • 检查 IAM 权限 - 我发现它只是将 CORS 错误视为一种一般错误 - 这对于诊断实际问题没有多大帮助。

标签: google-cloud-storage signed-url


【解决方案1】:

在 Google Cloud 支持团队的帮助下,我发现 ContentType 不正确。我将选项更改为:

contentType: 'application/x-www-form-urlencoded',

它成功了!

【讨论】:

    猜你喜欢
    • 2019-06-11
    • 2017-11-22
    • 1970-01-01
    • 2022-08-17
    • 2019-08-25
    • 2020-10-01
    • 2022-01-19
    • 2021-07-25
    • 2017-09-29
    相关资源
    最近更新 更多