【问题标题】:CORS Error on uploading image file to google cloud using signed url使用签名 URL 将图像文件上传到谷歌云时出现 CORS 错误
【发布时间】:2020-03-14 12:50:36
【问题描述】:

使用签名的 url 从本地主机将图像文件上传到谷歌云时出现 CORS 错误,如何避免?

生成signedUrl的代码:

    function get_v4_signed_url($bucket, $keyname, $contentType){

        $bucket = $this->storageClient->bucket($bucket);
        $object = $bucket->object($keyname);
        $url = $object->signedUrl(
            # This URL is valid for 15 minutes
            new \DateTime('120 min'),
            [
                'method' => 'PUT',
                'contentType' => $contentType,
                'version' => 'v4',
                "Access-Control-Allow-Origin" => "*"
            ]
        );
        return $url;
    }

来自存储桶的CORS:

gsutil cors get gs://bucket-name
[{"maxAgeSeconds": 3600, "method": ["GET", "POST", "PUT", "DELETE", "OPTIONS"], "origin": ["https://localhost:8443"], "responseHeader": ["goog-resumable", "Content-Type", "Authorization", "Content-Length", "User-Agent", "x-goog-resumable"]}]

Javascript 代码:

uploadFileToGcp(file, url) {

var xhr  = new XMLHttpRequest();
xhr.open('PUT', url);
xhr.setRequestHeader('Content-Type', file.type);
xhr.setRequestHeader("Access-Control-Allow-Origin","*");
xhr.onload = function () {
var res = JSON.parse(xhr.responseText);
console.log("res: "+res);
if (xhr.status == "200") {
hideLoadingDiv()
console.table(res);
} else {
console.error(res);
}
}
xhr.send(file);

}

来自谷歌云的回应:

Access to XMLHttpRequest at 'signed_URL' from origin 'https://localhost:8443' 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.

【问题讨论】:

  • 你是如何生成签名网址的?
  • 您是否在存储桶上设置了 CORS?如果没有,请参阅here
  • 错误的确切措辞/性质是什么?
  • 您好!请查看How to ask 部分并编辑您的问题。最好有您收到的确切错误消息以及您为得到它而采取的步骤,以便有人重现它并提供可能的解决方案
  • @AmitNaik 我添加了生成signedUrl的代码

标签: google-cloud-storage gsutil preflight


【解决方案1】:

我更改了 cors 文件:

[{"maxAgeSeconds": 3600, "method": ["GET", "HEAD", "DELETE", "PUT", "POST"], "origin": ["https://localhost:8443"], "responseHeader": ["Content-Type", "access-control-allow-origin"]}]

成功了

【讨论】:

    猜你喜欢
    • 2019-04-18
    • 1970-01-01
    • 2020-06-28
    • 2019-09-09
    • 2022-08-20
    • 2015-02-28
    • 1970-01-01
    • 2021-11-03
    • 2018-07-11
    相关资源
    最近更新 更多