Réti Opening
Réti Opening

Reputation: 474

Uploading to Google Cloud Storage not working even after enabling CORS

I have updated this cors.json to GCS bucket:

[
  {
    "origin": ["*"],
    "method": ["GET", "POST", "HEAD", "DELETE", "PUT"],
    "responseHeader": ["Content-Type"],
    "maxAgeSeconds": 3600
  }
]

using:

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

I have checked the preflight response:

access-control-allow-headers: Content-Type
access-control-allow-methods: GET,POST,HEAD,DELETE,PUT
access-control-allow-origin: *
access-control-max-age: 3600

Yet, the POST request to upload the file with this header:

:authority: storage.googleapis.com
:method: POST
:scheme: https
accept: */*
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9,ta;q=0.8
content-length: 913
content-type: application/json
dnt: 1
origin: https://099e00581bf2.ngrok.io

fails because of CORS error:

Access to XMLHttpRequest at 'https://storage.googleapis.com/...' from origin 'https://099e00581bf2.ngrok.io' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

What am I doing wrong?

Upvotes: 0

Views: 692

Answers (3)

Geek
Geek

Reputation: 519

Instead of using a pre-signed url approach you can try using REST API with an access token using POST request.

Here is the reference:

https://cloud.google.com/storage/docs/uploading-objects#rest-upload-objects

To generate access token :

gcloud auth print-access-token

Upvotes: -1

Réti Opening
Réti Opening

Reputation: 474

I found the answer to this problem. I was using "POST" method instead of "PUT". Since I created the signed url using action: 'write'

gcsfile.getSignedUrl({
    action: 'write',
    contentType: req.body.contentType,
    expires: Date.now() + 1000 * 60 * 60
})

I should be using "PUT" method, while calling https://storage.googleapis.com. Once I changed it, it worked like a charm.

But, this CORS error is so misleading. Hope GCS throws some meaningful error message in the future.

Upvotes: 4

Neo Anderson
Neo Anderson

Reputation: 6380

  • Start with this, just to cut all the possible causes from the list:
[
  {
    "origin": ["*"],
    "method": ["*"],
    "responseHeader": ["*"],
    "maxAgeSeconds": 3600
  }
]
  • Clear all the caches on your side.
  • Wait for 1-2 hours: the effects might be delayed due to intermediary caches as well.
  • Try again.
  • If it works, narrow down the SUPER permissive CORS conf that you created at step 1, by adding the methods that you want to be allowed, the origins and the response headers

If the steps above still don't solve your problem I would consider lecturing these two resources:
https://cloud.google.com/storage/docs/configuring-cors#storage-get-bucket-metadata-nodejs
https://cloud.google.com/storage/docs/configuring-cors#troubleshooting

Upvotes: 4

Related Questions