Firebase error with CORS when running on localhost
Asked Answered
B

6

8

I am getting the following error when running my project.

Failed to load https://us-centralx-xxx.cloudfunctions.net/xxx: 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:3000' is therefore not allowed access. The response had HTTP status code 500.

After reading many SO post, I found the following solution, where I need to add the Access-Control-Allow-Origin , Access-Control-Allow-Methods , and Access-Control-Allow-Headers

const HEADERS = {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    'Access-Control-Allow-Origin':  'http://localhost:3000/',
    'Access-Control-Allow-Methods': 'POST',
    'Access-Control-Allow-Headers': 'X-Requested-With,content-type'
};

However, the error still persist. How can i solve this ?

UPDATE

exports.uploadFile = functions.https.onRequest((req, res) => {
        res.setHeader("Access-Control-Allow-Origin", "*");

        res.setHeader('Access-Control-Allow-Methods', 'GET,POST,DELETE,HEAD,PUT,OPTIONS');
        res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');


    res.status(200).json({
        message: req.body
    });
});
Boldfaced answered 6/5, 2018 at 20:45 Comment(2)
This problem related to the backend server when you sending a pre-flight request the server should allow the request and response with headers. in your nodejs headers you need to allow http://localhost:3000 orgin to get an access.Eliason
This CORS error was very misleading. I got this problem when the client was mistakenly calling the function to a different region where the function didn't even exist. Once the client pointed to the correct region, no more CORS issue. We didn't have to code any res.setHeader() as suggested by your questions and by other answers.Yeaton
I
5

In your Node.js server set the appropiate headers to allow controlled CORS requests:

app.use((req, res, next) => {
  const origin = req.headers.origin;
  // arrayOfValidOrigins is an array of all the URL from where you want to allow 
  // to accept requests. In your case: ['http://localhost:3000'].
  // In case you want to accept requests from everywhere, set:
  // res.setHeader('Access-Control-Allow-Origin', '*');
  if (arrayOfValidOrigins.includes(origin)) {
    res.setHeader('Access-Control-Allow-Origin', origin);
  }

  // Here allow all the HTTP methods you want
  res.header('Access-Control-Allow-Methods', 'GET,POST,DELETE,HEAD,PUT,OPTIONS');
  // Here you allow the headers for the HTTP requests to your server
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  // Method to reference to the next Node.js function in your flow
  next();
});

Another option you have is to use the Express.js CORS package and configure it suitable to your needs.

Insensible answered 6/5, 2018 at 21:23 Comment(2)
I still get the same error. i have updated my post with the code I have. Can you please have a look.Boldfaced
I don't get why are you setting all the CORS directives inside the export of a function called uploadFile but if you are trying to do it by hand in each route endpoint you are going to waste a lot of time. I would advise you to set the CORS directives to your Node HTTP server / app and before the setting of the routes, in order to work properly.Insensible
P
4

I had this problem and got this same error when I realised that I hadn't deployed the function to Firebase. Deploying it stopped the error. So silly, but not that hard to make the same error.

Pontificals answered 14/3, 2019 at 12:23 Comment(1)
Exactly! Preflight OPTIONS requests, used for CORS checks, can be misleading as they often return a 404 status code even when CORS is configured correctly. This is because web servers might not always have a dedicated handler for OPTIONS requests on all routes. Don't immediately assume a CORS issue based solely on a 404 response to a Preflight request. Double-check your client side API URL root and such to ensure that the request URL, including the HTTP method and headers, aligns with your server-side settingsRiarial
N
3
import * as cors from 'cors'

const corsHandler = cors({origin: true})

export const myFunc = functions.https.onRequest(async (req: Request, res: Response) => {
   corsHandler(req, res, () => {
     // Do your work here
   })
)
Nefertiti answered 27/7, 2018 at 19:8 Comment(2)
While this code snippet may be the solution, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.Beebread
This was the way I solved itPaginal
P
0

Try to check logs from the Firebase function. In my case, the Chrome Devtools was showing a CORS error:

"severity": "ERROR",
"message": "Error: No Firebase ID token was passed as a Bearer token 
in the Authorization header. Make sure you authorize your request by 
providing the following HTTP header: Authorization: Bearer <Firebase ID Token> 

As the solution, missing the Barear token was the problem to be solved.

Be sure to check the logs.

Paginal answered 15/4, 2023 at 8:56 Comment(0)
S
0

I was able to get around these CORS errors by adding the Cloud Functions Invoker Role to my functions via https://console.cloud.google.com/functions/

  • I found instructions in the documentation here:

Authorize access with IAM

You use Identity and Access Management (IAM) to authorize identities to perform administrative actions on your functions, like creating, updating, and deleting them. You add principals (the identities you wish to enable, usually a user or service account email) to the function and then grant those principals the appropriate IAM roles. These roles include permissions that define the actions they are allowed to do.

Enabling access to a function

You can control actions on a function by granting or restricting roles to individual identities through IAM.

Adding principals and granting roles

  1. Go to the Google Cloud console
  2. Click the checkbox next to the function in which you are interested.
  3. Click Permissions at the top of the screen. The Permissions panel opens.
  4. Click Add principal.
  5. In the New principals field, enter one or more identities that need access to your function. This is usually a user or service account email.
  6. Select a role (or roles) from the Select a role drop-down menu. The roles you select appear in the pane with a short description of the permissions they grant.
  7. Click Save.

Note: In my case, the principal I added was allAuthenticatedUsers

Sources:

  1. https://github.com/firebase/functions-samples/issues/395#issuecomment-605025572
  2. https://www.reddit.com/r/reactjs/comments/fsw405/firebase_cloud_functions_cors_policy_error/
Slipshod answered 19/3 at 8:29 Comment(0)
C
0

As you might still run into those errors with gen2 functions this is how to solve it without an extra package: https://firebase.google.com/docs/functions/http-events?gen=2nd#configuring_cors_cross-origin_resource_sharing

onRequest({cors: ["*"]} async (request, response) => {
  //your code
});
Cantor answered 31/8 at 15:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.