1
votes

I am getting CORS error while uploading image file to google cloud from localhost using signed url,how to avoid it?

Code To generate 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 from bucket:

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 Code :

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);

}

Response from google cloud:

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.
1
how are you generating signed url?Amit Naik
Have you set up CORS on your bucket? If not, see here.FallenWarrior
What is the exact wording/nature of the error?Kolban
Hello! Please have a look at the How to ask section and edit your question. It would be nice to have the exact error message that you get and the steps that you did to get to it in order for someone to reproduce it and provide a possible solutionsiamsot
@AmitNaik I have added the code through which I am generating the signedUrlshreyanshu agarwal

1 Answers

3
votes

I changed the cors file :

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

and it worked