Home > front end >  Google Cloud Function Cors Error Only When Error is Thrown
Google Cloud Function Cors Error Only When Error is Thrown

Time:08-11

Dealing with a google cloud function that receives and responds as expected when there are no errors, however IF the function throws an error, on the client-side (Chrome) I receive a CORS error. I can't figure out if the issue is with how I am handling CORS or if it is because of a misuse of throw new function.https.httpsError.

Unsure if its related, the thrown error appears to be thrown AFTER the execution of the function finishes (based on logs).

  • I have set the function to be available to allUsers in the console.
  • I am using the cloud console to edit the function.
  • I did try using cors package

cloud function:

/**
 * Responds to any HTTP request.
 *
 * @param {!express:Request} req HTTP request context.
 * @param {!express:Response} res HTTP response context.
 */
const { initializeApp } = require('firebase-admin/app');
const { getFirestore, Timestamp, FieldValue } = require('firebase-admin/firestore');
const { getAuth } = require('firebase-admin/auth');
const functions = require('firebase-functions');
const app = initializeApp();
const db = getFirestore();

exports.registerUser = (req, res) => {
    let registerDetails = req.body.data;
    res.set('Access-Control-Allow-Origin', '*');
    if (req.method === 'OPTIONS') {
    // Send response to OPTIONS requests
      res.set('Access-Control-Allow-Methods', 'GET, POST')
      res.set('Access-Control-Allow-Headers', 'Content-Type, Accept')
      res.set('Access-Control-Max-Age', '3600')
      return res.status(204).send('')
    }

  return getAuth().createUser({
      email: registerDetails.Email,
      emailVerified: false,
      password: registerDetails.Password,
      displayName: registerDetails.DisplayName,
      disabled: false,
    }).then((user)=>{
      const message = 'Registered user '   registerDetails.DisplayName   '.'
      console.log('Successfully created new user:', user.uid)
      return res.status(200).json({data: message })
//ALL OF THIS PART WORKS JUST FINE
    }).catch((error)=>{
      console.log('Error creating new user:', error.errorInfo.message)
      throw new functions.https.HttpsError("already-exists", error.errorInfo.message)
    //IF AN ERROR HAPPENS I SEE A CORS ERROR CLIENT SIDE
    })
  
};

Client Side Code:

const regUser = fbf.httpsCallable('RegisterUser');

regUser({
        FirstName: $('#registerFirstName').val(),
        LastName: $('#registerLastName').val(),
        DisplayName: $('#publicName').val(),
        Email: $('#regEmail').val(),
        Password: $('#regPassword').val()
      }).then((result)=>{
          $('#regInputHide').hide();
          $('#regResponse').show();
          $('#submitNewReg').hide();
          $('#regFuncResponse').text(result.data)   
          console.log(result.data)
      }).catch((err)=>{
        console.warn(err)
        //THIS WILL LOG "Error: internal
       //                           @ etc."
       //IN ADDITION TO THE CORS ERROR
      })

CodePudding user response:

You are mixing the APIs for a HTTP Event Cloud Function with a Callable Cloud Function.

You need to use one or the other or at least add in the code to format the response from your function in a way that httpsCallable can parse.

// Exporting/using a `(req: Request, res: Response) => any` function is a
// HTTP Event Cloud Function pattern
exports.registerUser = (req, res) => {  
/* ... */
  // Returning a Promise chain is a Callable Cloud Function pattern
  return getAuth().createUser({
/* ... */
      // sending a response is a HTTP Event Cloud Function pattern
      return res.status(200).json({data: message })
/* ... */
      // throwing HttpsError instances is a Callable Cloud Function pattern
      throw new functions.https.HttpsError("already-exists", error.errorInfo.message)
/* ... */
}
  • Related