Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to test locally using firebase due to CORS restriction

My current usecase is simple, I just need to make a post request to a cloud function I have locally developed.

The catch is, when I fire

firebase serve

the hosting is deployed on localhost:5000

and cloud functions are deployed on localhost:5001

These both are from different origin as port is different. Thus, when the browser sends the initial preflight request, it fails with error message

Failed to load http://localhost:5001/projectname/region/sendEnquiry: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:5000' is therefore not allowed access.

How can I set the headers for testing this locally?(Again here I am not a pro, I am guessing I will have same origin when I decide to deploy in production. If not, anyways I will still need the solution)

Thanks.

like image 821
Abhishek Agarwal Avatar asked Nov 08 '22 08:11

Abhishek Agarwal


1 Answers

Google restricts certain calls but you can configure CORS for your firebase projects. It's hard to find how to do this by means of the very confusing docs, took me a while to find the right way.

Follow these steps:

  1. Go to console.cloud.google.com
  2. At the top left, select your Firebase project
  3. Click the terminal icon at the top left (looks like >_)
  4. In the terminal that opens, click the three dots icon and select 'Upload file'
  5. Upload a file called cors.json with the following contents:
[
 {
   "origin": ["*"],
   "method": ["GET"],
   "maxAgeSeconds": 3600
 }
]
  1. In the terminal, run the following command: gsutil cors set cors.json gs://yourbucketname.appspot.com (change the url)

This allows any GET requests from other origins.

like image 130
paddotk Avatar answered Nov 14 '22 23:11

paddotk