簡體   English   中英

Google Cloud Function Cors 僅在引發錯誤時出錯

[英]Google Cloud Function Cors Error Only When Error is Thrown

處理沒有錯誤時按預期接收和響應的谷歌雲 function,但是如果 function 拋出錯誤,在客戶端(Chrome)我收到 Z5A8FEFF0B4BDE3EEC924B7976 錯誤。 我不知道問題是我如何處理 CORS 還是因為誤用throw new function.https.httpsError

不確定其是否相關,在 function 執行完成后(基於日志)似乎拋出了拋出的錯誤。

  • 我已將 function 設置為對控制台中的所有用戶可用。
  • 我正在使用雲控制台編輯 function。
  • 我確實嘗試過使用 cors package

雲 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
    })
  
};

客戶端代碼:

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
      })

您正在將HTTP 事件雲 Function可調用雲 Function的 API 混合。

您需要使用其中一個或至少添加代碼以以httpsCallable可以解析的方式格式化來自 function 的響應。

// 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)
/* ... */
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM