jabberwoo
jabberwoo

Reputation: 521

How to set CORS of a public Google Cloud Storage buckets to avoid errors when using javascript fetch function?

When I ran the following codes to fetch data (.json format) stored in my public GCS bucket, something went wrong.

async function getData() {
  const carsDataReq = await fetch(...);
  const carsData = await carsDataReq.json();  
  const cleaned = carsData.map(car => ({
    mpg: car.Miles_per_Gallon,
    horsepower: car.Horsepower,
  }))
  .filter(car => (car.mpg != null && car.horsepower != null));
  console.log(cleaned);
  return cleaned;
}

The error message looks like the following:

Access to fetch at '...' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I tried to set CORS of the bucket by the following .json file:

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

but the error still showed up. How to fix it?

Upvotes: 2

Views: 819

Answers (1)

tzovourn
tzovourn

Reputation: 1321

Posting my comment as an answer to give visibility to other users.

ERROR

Access to fetch at '...' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

This means that the server that hosts the resource needs to have CORS enabled. What you can do on the client side is set the mode of fetch to CORS.

fetch(request, {mode: 'cors'});

Credits to this post for all the information provided. Check it for more details.

Upvotes: 2

Related Questions