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.
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