Search code examples
javascriptfirebasefetchfirebase-storage

How to fix error when fetching file from firebase storage?


I am trying to make a page that lets you upload a file and search for certain values in it, but when I am trying to fetch the file from firebase storage it is giving me an error

Access to fetch at 'theurl' from origin 'mysite' 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.

Yes, I have tried to set the mod to no-cors, which kinda works but the fetch returns a blank txt file. Here is my code, please help. Thanks

storageRef.child('thefilepath').getDownloadURL().then(function (url) {
    document.getElementById("atextbox").value = url
})

var dictionaryurl = document.getElementById("atextbox").value

fetch(dictionaryurl)
    .then(r => r.text())
    .then(t => {mycodethatrunsafter});

Solution

  • This is a server issue. You need your server (at Firebase?) to allow access from the domain your are trying to upload/download the file. If the Firebase server is not of your own, you'll need an anti-CORS proxy in behind, whether owned by you or one of the publicly accessible. An anti-CORS proxy takes a request with an URL in it (for example, in a HTTP GET or POST variable) and makes the request to the desired server. Finally, sends the response to the original client, with the correct HTTP headers (without CORS or with CORS rules allowing the domain).

    Edit

    To configure your Firebase Storage, follow this:

    Step 3: Configure Cross-Origin Resource Sharing (CORS) We can use the gsutil cors command to configure CORS on a bucket:

    gsutil cors set cors.json gs://mlc-agira-271a8.appspot.com
    

    cors.json will contain:

      [
       {
         "origin": ["yourapp.url.com"], // Or * if you want to allow every one
         "method": ["GET"], // And/or POST, PUT or whatever you use
         "maxAgeSeconds": 3600
       }
     ]