【问题标题】:Invoking Firebase Function from Firebase hosting code blocked by CORS从被 CORS 阻止的 Firebase 托管代码调用 Firebase 函数
【发布时间】:2021-08-10 19:38:58
【问题描述】:

我已经使用 functionshosting 功能初始化了一个模板化 Firebase 项目。

我取消了模板化 HTTP 函数的注释:

export const helloWorld = functions.https.onRequest((req, res) => {
  functions.logger.info("Hello logs!", {structuredData: true});
  res.send("Hello from Firebase!");
});

并且还在模板化的public/index.html文件中添加了以下代码:

const functions = firebase.functions();
const helloWorld = functions.httpsCallable('helloWorld');
helloWorld().then((res) => { console.log(res); });

我已经尝试过使用多种配置来完成这项工作:

  1. 用于托管的 Firebase 模拟器,调用已部署的 Firebase 功能。
  2. 用于托管的 Firebase 模拟器,调用模拟函数(Firebase 函数模拟器)。
  3. 已部署的主机,调用已部署的 Firebase 函数。

所有配置都会产生以下结果:

Access to fetch at 'https://us-central1-my-project.cloudfunctions.net/helloWorld' from origin 'http://127.0.0.1:5000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

我没有更改模板化、自动生成的 Firebase 代码中的任何内容,但没有我所说的内容。

我错过了什么?

【问题讨论】:

    标签: javascript node.js firebase google-cloud-functions cors


    【解决方案1】:

    您实际上混淆了HTTP Cloud FunctionsCallable Cloud Functions

    您的 helloWorld Cloud Function 代码对应于 HTTP 代码,但您前端的代码(即 public/index.html)调用了 Callable 代码。

    您应该将 helloWorld Cloud Function 作为 REST API 调用,例如,使用 fetch 或 Axios。

    【讨论】:

      【解决方案2】:

      您将 onRequestonCall 错误匹配,这是两种不兼容的不同方法,由于找不到它而导致 CORS 错误。

      更改您的 http 类型:

      • 发件人:.onRequest((req, res)
      • 收件人:.onCall((data,context)

      来源:onRequestonCall

      一般 CORS 核对清单

      • 确保功能已部署。
      • 确保函数是正确的类型 onCallonRequest
      • 确保函数名称正确。错字和大小写很重要
      • 确保函数代码本身不会引发错误。帮助调试的模拟器。
      • 确保您的区域与该区域匹配函数,并使用该区域调用它。

      将可调用函数部署到特定区域:

      const functions = require('firebase-functions');
      exports.yourFunc = functions.region('europe-west2').https.onCall(async (data, context) =>{
        // ... 
      })
      

      从客户端调用特定区域的函数:

      import firebase from 'firebase/app'
      import 'firebase/functions'
      firebase.app().functions('europe-west2').httpsCallable('yourFunc')
      Note: firebase.app().function... vs firebase.app.function...
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-02-15
        • 2020-09-02
        • 2020-10-16
        • 1970-01-01
        • 2023-03-29
        • 2020-07-25
        • 2019-10-16
        相关资源
        最近更新 更多