How to fix a No `Access-Control-Allow-Origin’ error message on Google Cloud Storage

Sélom
1 min readNov 21, 2017

I’m trying to download a file via jQuery Ajax. The file is stored a file on Google Cloud Storage. My domain is http://localhost:8888/. My initial code is shown below:

$.ajax('https://my-awesome-bucket/my-file.txt', {
dataType: 'text', // type of response data
success: function (data,status,xhr) {
console.log('Awesome!');
},
error: function (jqXhr, textStatus, errorMessage) {
console.log('Oops! An error has occurred.');
}
});

Obviously, the code above presents a Cross Origin issue since my domain (http://localhost:8888/) is different from the domain where the file that I’m trying to download is hosted. When I checked my browser console, I got an error message saying:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin http://localhost:8888 is therefore not allowed access.

How to fix this?

1- Follow the steps listed here https://cloud.google.com/storage/docs/gsutil_install to install gsutil

2- Next, cd into the root of your project and create the file cors-json-file.json with the content below:

[
{
"origin": ["*"],
"method": ["*"]
}
]

3- Run the command below

gsutil cors set cors-json-file.json gs://my-awesome-bucket

Notice that to run the command, we used gs:// instead of https://

Now run you ajax script again. If the issue persists, change the dataType from text to jsonp.

UPDATE: Obviously, this is a hack and shouldn’t be used in production. The best way to fix this issue, is to upload your project to the bucket which contain the file that you are requesting. Thanks for the feedback Lukas Zech

--

--

Sélom

Software Engineer | Fullstack Web Dev | Node.js ~ Laravel ~ React.js