【问题标题】:CORS error when calling Firebase cloud function with httpsCallable()使用 httpsCallable() 调用 Firebase 云函数时出现 CORS 错误
【发布时间】:2020-02-03 20:34:58
【问题描述】:

我正在尝试从我的 React 客户端调用我的 Firebase 云函数。

  1. 我能够使用 HTTP 请求成功调用这些函数(如 here 所述)。这需要在云功能中设置完整的 Express 应用。

  2. 现在我尝试使用httpsCallable()(如here 所述)直接从我的客户端调用云功能。与通过 HTTP 请求调用相比,这种方法似乎有几个优点。但是使用这种方法我得到以下 CORS 错误:

CORS 政策已阻止从源“http://localhost:3000”获取“https://us-central1-myapp.cloudfunctions.net/helloWorld”的访问权限

我该如何进行这项工作?值得麻烦吗?这真的是首选方式吗?

这是我的云功能:

import * as functions from 'firebase-functions';

export const helloWorld = functions.https.onRequest((request, response) => {
    response.send('Hello from Firebase!');
});

这是我从客户那里调用它的方式:

const sayHello = async (): Promise<string> => {
    const helloWorld = firebase.functions().httpsCallable('helloWorld');
    const result = await helloWorld();
    return result.data;
};

【问题讨论】:

    标签: firebase cors google-cloud-functions


    【解决方案1】:

    通过做

    const helloWorld = firebase.functions().httpsCallable('helloWorld');
    const result = await helloWorld();
    

    你确实在调用Callable Cloud Function但是通过如下定义被调用函数

    functions.https.onRequest((request, response) => {})
    

    您正在定义一个HTTPS Cloud Function 这是不同的

    您应该将您的云函数定义为可调用函数,如下所示:

    export const helloWorld =  = functions.https.onCall((data, context) => {
      return { response: 'Hello from Firebase!' };
    });
    

    【讨论】:

    • 非常感谢,雷诺!您对 Callable Cloud 函数与 HTTPS Cloud 函数的解释比文档清晰得多。我希望文档在这两个部分之前有一个概述部分,解释差异并警告不要将两者混为一谈。
    猜你喜欢
    • 2020-07-07
    • 1970-01-01
    • 1970-01-01
    • 2020-08-08
    • 2020-07-13
    • 2021-09-08
    • 2022-09-26
    • 2021-08-14
    • 1970-01-01
    相关资源
    最近更新 更多