首页 > 解决方案 > 在本地运行 Firebase 可调用 HTTP 云函数

问题描述

我已经部署了一个可调用函数,比如说foo,使用

firebase deploy --only functions:foo

我在 Flutter 中使用以下命令调用它:

var result = await FirebaseFunctions.instance.httpsCallable('foo')();
var data = result.data;

都好。但我想在 Firebase 模拟器中运行这个功能。当我跑

firebase emulators:start --only functions

我可以看到模拟器启动并运行,我正在使用以下方法将 Flutter 应用程序连接到模拟器:

FirebaseFunctions.instance.useFunctionsEmulator('localhost', 4000);

但是,我不知道如何foo使用 Firebase Emulator 在 Flutter 中调用 callable。我看到了这个相关的线程,但它并没有真正回答我的问题。


编辑:

这是控制台输出:

✔  functions[us-central1-foo]: http function initialized (http://localhost:5001/my_project/us-central1/foo).

┌─────────────────────────────────────────────────────────────┐
│ ✔  All emulators ready! It is now safe to connect your app. │
│ i  View Emulator UI at http://localhost:4000                │
└─────────────────────────────────────────────────────────────┘

┌───────────┬────────────────┬─────────────────────────────────┐
│ Emulator  │ Host:Port      │ View in Emulator UI             │
├───────────┼────────────────┼─────────────────────────────────┤
│ Functions │ localhost:5001 │ http://localhost:4000/functions │
├───────────┼────────────────┼─────────────────────────────────┤
│ Firestore │ localhost:8080 │ http://localhost:4000/firestore │
└───────────┴────────────────┴─────────────────────────────────┘
  Emulator Hub running at localhost:4400
  Other reserved ports: 4500

我试过了

useFunctionsEmulator('localhost', 4000);
useFunctionsEmulator('localhost', 5001);

但他们都在调用时抛出以下错误httpsCallable('foo')但没有模拟器,这个函数确实有效。

[错误:flutter/lib/ui/ui_dart_state.cc(209)] 未处理的异常:[firebase_functions/unavailable] UNAVAILABLE

标签: firebasefluttergoogle-cloud-functionsfirebase-tools

解决方案


我怀疑您的主机和端口值可能不正确。当您启动模拟器时,日志将显示用于各种模拟器的所有端口。还有firebase.json包含模拟器端口配置的文件。

此外,localhost客户端不会自动识别。对于 Android,您可能必须networkSecurityConfig通过创建网络安全配置 xml 在清单中进行配置。对于 iOS,我认为应该在plist文件中添加一些内容 - 必须检查确认。

一旦您的客户能够访问localhost(隐式或显式),您就可以连接到您的模拟函数。例如,我在我的代码中明确声明了主机值(预计不会在重新启动后更改)。

这是我在 Kotlin 中使用的代码:

functions = FirebaseFunctions.getInstance()
    /*
    * Emulator
    * */
    if (emulatorMode) { //Local Testing
        functions.useEmulator("10.0.2.2", 5001)
    } else { //Live
        functions = Firebase.functions
    }

    // Call the function and extract the operation from the result
    return functions
        .getHttpsCallable(function)
        .call(inputData)
        .continueWith { task ->...

推荐阅读