0

I have a firebase function which serves a website as per below:

const app = express();
app.use(express.static("my-website"));
exports.app = functions.https.onRequest(app);

Where my-website has my-website/subfolder/index.html and my-website/subfolder/index.js. I have deployed the function and it successfully serves up index.html and index.js. However, index.js is attempting to download a file from Cloud Storage but is getting the following error:

Access to XMLHttpRequest at 'https://storage.cloud.google.com/my-project.appspot.com/my-project-files/data.csv' from origin 'https://us-central1-my-project.cloudfunctions.net' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I am not using the firebase cloud storage web library, because the code is already written using the d3.js library as per below, and I can't change it:

d3.queue()
    .defer(
      d3.csv,
      "https://storage.cloud.google.com/my-project.appspot.com/my-project-files/data.csv"
    )
    .defer(d3.json, "data/config.json")
    .defer(d3.json, "data/geog.json")
    .await(ready);

This code generates the following request:

:authority: storage.cloud.google.com
:method: GET
:path: /my-project.appspot.com/my-project-files/data.csv
:scheme: https
accept: text/csv,*/*
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9
cache-control: no-cache
origin: https://us-central1-my-project.cloudfunctions.net
pragma: no-cache
referer: https://us-central1-my-project.cloudfunctions.net/app/my-website/subfolder/index.html
sec-fetch-dest: empty
sec-fetch-mode: cors
sec-fetch-site: cross-site
user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36

I have set a CORS policy on my bucket to allow requests from my cloud functions, gsutil cors get gs://my-project.appspot.com returns:

[{"maxAgeSeconds": 3600, 
"method": ["GET"], 
"origin": ["https://us-central1-my-project.cloudfunctions.net"], 
"responseHeader": ["Content-Type"]}]

I am not sure where to go from here. What am I doing wrong?

Max888
  • 1,382
  • 9
  • 20
  • Does this answer your question? [Enabling CORS in Cloud Functions for Firebase](https://stackoverflow.com/questions/42755131/enabling-cors-in-cloud-functions-for-firebase) – Soni Sol May 28 '20 at 18:11

2 Answers2

0

This is a fairly common error for people setting up webapps. To make sure that sites are secure and to prevent code injections, browsers prevent cross-origin requests. Mozilla has a great manual on how to solve this. https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors

Darrow Hartman
  • 381
  • 3
  • 16
0

I worked out that the problem is the Cloud Storage doesn't actually let you allow CORS for the storage.cloud.google.com, instead you have to use storage.googleapis.com.

Max888
  • 1,382
  • 9
  • 20