5
votes

I'm trying to get files via AJAX from google cloud storage on my local host. I have done the following:

Set the CORS for my bucket via gsutil:

gsutil cors set cors.json gs://my-project

where the cors.json file is:

[
  {
    "origin": [
      "*"
    ],
    "responseHeader": ["Origin", "Accept", "X-Requested-With", "Authorization", "Content-Type",     "Content-Length", "Accept-Encoding", "X-CSRF-Token"],
    "method": [
      "GET",
      "OPTIONS"
    ],
    "maxAgeSeconds": 1
  }
]

I have verified it with gsutil cors get gs://my-project

Then for each file I have made it public, both through the node.js client library when the file is uploaded:

bucket.file(object.name).makePublic()

through the console, and through the gsutil:

gsutil -m acl set -R -a public-read gs://my-project

Then in my ajax request, I also send headers:

$.ajax({
            method: "GET",
            url: "https://googleapis.com/storage/v1/b/my-project/o?delimiter=audio",
            headers: {
                'Access-Control-Allow-Origin': '*'
            },
            crossDomain: true,
        }).done((data) => {
            console.log(data)
        })

and I still get a cors error:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

How do I get past CORS?

1

1 Answers

3
votes

You're using "googleapis.com" instead of "www.googleapis.com". Add the "www" and your code will work.

It looks like you're not doing any authentication, so you'll also need to make sure that your bucket allows anonymous users to list objects (gsutil acl ch -g allUsers:R gs://bucket-name will set that).

Next, for anonymous requests, it's a good practice to add an API key parameter associating the request with your Google Cloud project. GCS will allow completely anonymous requests, but they may be blocked if they get too frequent.

Finally, the CORS policy on a bucket is only respected by the XML API. The JSON API, which is the one with the endpoint of "www.googleapis.com", will happily respond to cross-origin requests without the need to set any special properties on the bucket.