Search code examples
angularfirebasegoogle-cloud-functionsfirebase-hosting

Enabling CORS in Firebase Hosting


I have this really annoying issue with CORS and my Google Cloud function...

the error I get is:

Access to XMLHttpRequest at [My function URL] from origin 'http://localhost:4200' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.

Ive already tried to handle it on the function side with the following code:

if request.method == 'OPTIONS':
        headers = {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'GET',
            'Access-Control-Allow-Headers': 'Content-Type',
            'Access-Control-Max-Age': '3600'
        }

        return ('', 204, headers)

and then added in the main return with:

headers = {
            'Access-Control-Allow-Origin': '*'
        }
....

return(json.dumps(data), 200, headers)

this doesnt work....

I also tried with the firebase.json headers approach and also not working...

even tried with the HttpHeaders in angular like so:

const headers = new HttpHeaders() 
      .set("Access-Control-Allow-Origin", "*") 
      .set("Access-Control-Allow-Methods", "POST, GET, OPTIONS") 
      .set('cache-control', 'no-cache')

also not working.....

then I tried with a proxy (just to check if that is the actual problem) added the proxy.config.json and of course in the dev it just works...

but the problem is, I need to be able to upload the Angular app to the firebase hosting so how can I fix the CORS error in the backend?


Solution

  • Well its solved now, the issue:

    I have the CORS headers in the cloud functions (server side) AND in the webApp side too this somehow is not allowed so i just removed the code from the webapp side and left the code only in the cloud function (server side) this solved the problem...

    Thanks to all!