ChatGPT解决这个技术问题 Extra ChatGPT

Firebase 可调用函数 + CORS

https://i.stack.imgur.com/QO8rs.png

I can't enable Cors since I don't have access to the request and response on the onCall function. This is my function:

exports.UserInvitation = functions.https.onCall((data, context) => {
  const email = data.email


  return new Promise((resolve, reject) => {
    admin.auth().createUser({
      email: email,
      emailVerified: false,
      password: password
    }).then(resolve).catch((err) => {
      console.error(err.code)
      reject(new functions.https.HttpsError(err.code, err.message))
    })
  })
})

And this is how I call it:

functions.httpsCallable('UserInvitation')({ email: this.input.value }).then((data) => {
      console.log('Sent invitation:', data)
})

Firebase-functions package.json:

{
  "name": "functions",
  "description": "Cloud Functions for Firebase",
  "scripts": {
    "serve": "firebase serve --only functions",
    "shell": "firebase functions:shell",
    "start": "npm run shell",
    "deploy": "firebase deploy --only functions",
    "logs": "firebase functions:log"
  },
  "dependencies": {
    "bluebird": "^3.5.1",
    "firebase-admin": "~5.12.0",
    "firebase-functions": "^1.0.1"
  },
  "private": true
}

WEB SDK Firebase version: 4.13.1

CORS should be automatically handled by the onCall handler. I suspect that the error message about CORS is inaccurate, and a result of the function returning 500 internal. What do you see in the Functions Logs in the Firebase Console?
You're right, the problem is with my error handler. The documentation says I can reject a promise with a instance of functions.https.HttpsError, but even though I'm doing that I'm getting a 500 error on the client. How can I fix that?
Even if I remove my return statement and add a throw new functions.https.HttpsError('test/code', 'error message') it only returns a object with message and status equals to "INTERNAL"
Ah yes, the status code passed to HttpsError cannot be test/code. It must be one of the standard codes listed here: firebase.google.com/docs/reference/functions/…
@bklimt please create an answer with this comment and I'll accept it :) I believe this detail should be added to the firebase onCall documentation

A
Aido

For anybody else who has arrived here searching firebase callable functions cors errors, here's my checklist:

Ensure the function is deployed. Ensure the function name is correct. I was calling recalculatY when it should have been recalculateY. Got a cors error for some reason. Ensure the function code itself is not throwing an error. Use the emulator to help. This didn't throw a cors error still helpful to know. Ensure your regions match - I am using europe-west2. I had to both deploy the function with that region, and call it using the region. For a while, I assumed the client would infer the correct region if the function name was correct. That was not the case.

Deploying a callable function to a specific region:

// This is the file in which you define your callable function.
const functions = require('firebase-functions');
...
exports.yourFunc = functions.region('europe-west2').https.onCall(async (data, context) => {
    ...
})

Calling a function in a specific region from the client (in this case, a vuejs web app):

// In my case, this is a vuex store file, but it is safe to assume this is plain old javascript
import firebase from 'firebase/app'
import 'firebase/functions'
...
firebase.app().functions('europe-west2').httpsCallable('yourFunc')

Note: firebase.app().function... vs firebase.app.function...


This made it for me! Didn't have region in the calling.
Basic checklist... you saved me with "Ensure the function name is correct"
Thanks for this. It was #1 for me. I thought I had deployed it.
saved my day. I was gonna edit a whole lot of code.
K
Kitson

For anyone looking at this post Jan 2020..

Found this answer on Reddit (https://www.reddit.com/r/reactjs/comments/fsw405/firebase_cloud_functions_cors_policy_error/)

Turns out on 15th Jan 2020, Google changed the security settings where all new functions no longer have a Cloud Functions Invoker. This means that all newly created functions will have their access forbidden, thus resulting in a CORS policy block. Here is how you fix it, as it's not all that obvious: https://cloud.google.com/functions/docs/securing/managing-access-iam#allowing_unauthenticated_function_invocation


Good lord. What a mess of a bug to find. Thank you!
but this will allow all users to call this function I mean I have done that CORS error gone but now I can trigger that function from postman with out any headers!! is this the only way @Kitson
I was using .https.onCall(async (data, context) => { ... }) and the context has access to teh auth user context.auth. I was then using this to check permissions and throw an error for unauthenticated users.
This is infuriating - for such a big company the docs are all over the place on this topic. How was that not all over the place when it happened? Thank you.
Thanks, this worked for me. Interesting tidbit to add is that I deployed 3 functions at the same time and only 1 had this issue.
i
iStuart

I had this problem with some of my Firebase functions but not others. I eventually fixed it by doing this:

Commenting the function out in index.js Running firebase deploy Entering y at the prompt to delete the function Waiting for 5 to 10 minutes Removing the comments around the function and running firebase deploy again

Without any changes to the function itself, it now runs without any CORS issues.


Unbelievable, after spending several hours trying all the different solutions here, I deleted every function and redeployed them again and suddenly, they started working without any CORS issues. During that time I was still unsure whether I would also have to do @Nikita's solution for https.onCall(..) functions where the user is authenticated (because nothing made them work). Answer is no - complete deletion and redeploy fixed the issue.
I tried every single thing in this thread. But this one was the solution for me. Just delete all cloud functions once. Then redeploy and it works again!
I did something extremely similar: deployed THE EXACT SAME FUNCTION with a different name: great success. Flipped a table and moved on.
I tried all kinds of solutions and yes, the solution was the same for me, just remove all the functions and deploy them again. What the actual.. I've been sitting with this error for hours wondering what and how to solve the issue and then it is just "delete and try again"... feel so stupid.
I tried every other possible solution ... No offense but I tought this never gonna work because of that I even never tried that but man ... I can say this was the issue. Thank you !
D
David Constantine

Probably many will hit this issue with the emulator and cors messages.

I havn't seen my case discussed in any discussion I've seen in Google, I do have seen many "can't reproduce", maybe my case will shed some light:

In my case the issue was that I wasn't running the hosting from the firebase emulator.

When you run your react app via npm start - while the functions run via firebase emulators:start, you will see the Cors errors.

So when testing cloud function calls, rather using npm start, you should do npm run build and then access the app from the emulator...

Search for something like: "hosting: Local server: http://localhost:5000"

few notes -

Your functions should also work against the emulator via

const functions = firebaseApp.functions('europe-west3');// lets assume thats your region functions.useFunctionsEmulator('http://localhost:5000');


P
Pietro Coelho

My issue was not with CORS, but with my error handler. Instead of rejecting the promise, I've used throw directly in the catch handler.

catch((err) => {
  throw new functions.https.HttpsError('unknown', err.message, err)
})

that seems extremely weird to me. Rejecting inside a promise that you are returning in the cloud function, feels to me like it's the exact same thing as throwing...
N
Nikita Jerschow

For those facing this error after enabling firebase on an existing GCloud project, there is some complexity which is not taken care of automatically as it would be if it were just a firebase app.

I had this specific problem because I wanted my firebase function to be publicly accessible, but you have to specifically configure this if you're using google's Cloud Functions.

Here are the steps to fix:

Go to the cloud function tab Select your cloud function (check box) Click "Add members" under Permissions tab in the right side Enter "allUsers" under "New memebers" Select Role as "Cloud Functions -> "Cloud Functions Invoker" Save Test your cloud function by just pasting it in the browser

Cheers


C
Code Spirit

If none of the above is helping: In my case the reason was that I havent correctly set up my regions. This can especially happen when using 3rd party libraries.


Where do you set the regions? I'm using one, but only in the calling: exports.myf = functions.region("europe-west3").https.onCall(...). Is there some other place I should touch?
You can wrap it in your own module and use this instead of the original functions module so you only have to call region once.
My problem was solved by @Aido's answer. Needed to also have the browser code tell Firebase which region to use.
s
steventilator

I previously had deployed my function as an HTTP function (https.onRequest), then switched to a callable function (https.onCall). Firebase did not recognize this change.

I solved the problem by removing the function and deploying without it, then putting the function back in and deploying again.


W
Wilson

If you are using multiple environments (Firebase Projects) to separate development and production (i.e Project-dev, Project-prod), make sure you have switch to the desirable environment. In my case, running this worked:

firebase use default

thanks that worked after I started my local emulator again. But do you also know why? What does the firebase environment have to do with my local emulator?
B
Bao Pham

For me, I had to allow access to allUsers for the function.

Go to Google Cloud Platform Console Cloud Functions. You can click on the Detailed usage stats in the Functions tab on Firebase Console Go to the Permissions tab Click Add Add appropriate permission


M
MoOp

I had the same issue. My solution was to open my Firebase project in https://console.cloud.google.com and navigated to cloud functions page.

Look for your function name go to its permission page, and add new role "Cloud Functions Invoker" to "allUsers" member.


love you! ❤️ saved my day
B
BHAR4T

Errors should be as given in https://firebase.google.com/docs/reference/functions/functions.https.HttpsError I deployed callable function after changed function name and it's working.


A
A Johnson

I got the same error when I tried to create a custom token for signing in a firebase user. I have attached my code below. However, I later discovered that the issue was due to attempting to create multiple tokens, by calling the function several times with the same parameters.

export const getCustomToken = functions.https.onCall((params: any) => {
 return admin.auth().createCustomToken(params).then((token) => {
   return token;
  }).catch((error) => {
    console.log(error);
    return null;
  });
 });

SOLUTION I solved the issue by first checking that the user is logged out before attempting to sign in. So I suggest that you first check if the user your trying to create already exists. I know this is a bit late but I hope this helps some one else.

this.fireAuth.currentUser.then((signedInAlready) => {
  if (signedInAlready) {
    return this.fireAuth.signOut().then(() => getCustomToken());
  } else {
    return getCustomToken();
  }
});

In your firebase functions you can check for an existing user as follows:

admin.auth().getUserByEmail('your-email').then((userExists) => {
if (userExists) {
  // return user
} else {
  // create a new user
}});

K
Kian Aghaei

Basically, I did everything mentioned in tones of pages and answers regarding CORS error for onCall cloud functions, from changing the region or manually adding the invoke permission to more obvious ones, nothing worked for me. Just turned the onCall onto OnRequest and it works.


y
yehonatan yehezkel

i try every thing - nothing work.

delete all function - not work... set the cors header - you cant do it in callable function add the "Cloud Functions Invoker" permission - it was allredy set.. add try catch -didnt help

till i found someone that tald to change the rewrite rules in angular.json only this work for me here is the complete guide from firestore docs - pay attantion - it works only from region us-central1

how to solve CORS on firestore onCall function with context

anoter docs on CORs problem in callable functions

my lib versions

angualr 13

"@angular/fire": "^7.2.0",

"firebase": "^9.4.0",

F
Frederik Agger

What worked for me was to remove the region params in my cloud function and then redeploy.

From functions.region("europe-west2").https.onCall(async (data) => {..

to functions.https.onCall(async (data) => {..