如何在 us-central1 以外的区域使用 httpsCallable for web

Thi*_*man 5 firebase google-cloud-functions

我部署了一个云函数,如下所示:

export const publishVersion = functions
  .region("europe-west2")
  .https.onCall(async (data, context) => {}
Run Code Online (Sandbox Code Playgroud)

然后在我的 Web 客户端中,我定义了一个函数来调用它:

import { functions } from "firebase";

const callPublishVersion = functions().httpsCallable("publishVersion");

export function publishVersion(
  guidelineId: string,
  guidelineReference: string
) {
  return callPublishVersion({
    id: guidelineId,
    reference: guidelineReference
  });
}
Run Code Online (Sandbox Code Playgroud)

请注意,我包装函数的唯一原因是在我的客户端中进行严格的输入,但这不是这个问题的重点。

问题是,如果我在本地服务器 (localhost) 上运行 Web 客户端并调用该函数,则有两件事似乎会出错。我收到 CORS 错误:

从源“ http://localhost:3000 ”获取“ https://us-central1-my-project.cloudfunctions.net/publishVersion ”的访问权限已被 CORS 政策阻止:对预检请求的响应未通过访问控制检查:预检请求不允许重定向。

而且,us-central1即使我的功能已部署到europe-west2. 当我部署 firebase-tools 时会告诉我 url 应该是什么:

? 函数[publishVersion(europe-west2)]:创建操作成功。函数 URL(发布版本):https ://europe-west2-baymard-gemini-dev.cloudfunctions.net/publishVersion

我在哪里/如何控制事物以防止出现此 CORS 错误,以及如何将 httpsCallable 定向到其他区域?

官方文件没有提到任何这一点。

- - 编辑 - -

我刚刚发现,如果我将该函数部署到 us-central1,它可以正常工作而不会出错。所以 CORS 部分不是问题(我将从标题中删除它),问题变成:如何配置 Web 客户端以调用正确的区域?

- - 编辑 - -

我在文档中注意到了这一点:

注意:要调用在默认 us-central1 以外的任何位置运行的函数,您必须在初始化时设置适当的值。例如,在 Android 上,您将使用 getInstance(FirebaseApp app, String region) 进行初始化。

这似乎是一个很好的指针,但我不知道如何为 web 配置它。所以我也会在标题中缩小范围。

Riu*_*ina 15

这是一个不同的版本,使用Modular Web-Version 9

import { initializeApp } from 'firebase/app';
import { getFunctions, httpsCallable } from "firebase/functions";

const app = initializeApp({
  // Auth stuff
});
// add the location string as you call getFunctions
const functions = getFunctions(app, "europe-west3");
const myFunction = httpsCallable(functions, "myFunction");
Run Code Online (Sandbox Code Playgroud)

  • 这是2022年最新最好的答案。 (4认同)

Thi*_*man 13

通过检查源代码找到它。所以这不在文档中,并且由于您可以获得函数实例句柄的所有不同方式,这有点令人困惑,但这是方法:

const app = firebase.app();
const functions = app.functions("europe-west2");
const callPublishVersion = functions.httpsCallable("publishVersion");
Run Code Online (Sandbox Code Playgroud)

  • 文档中提到了这一点:https://firebase.google.com/docs/functions/locations#client-side_location_selection_for_callable_functions (2认同)