首页 > 解决方案 > Flutter:无法访问 Firebase 云功能模拟器,找不到具有指定主机名的服务器

问题描述

虽然我可以调用已部署的 Cloud 函数,但使用 Firebase 模拟器会返回错误。

错误

 A server with the specified hostname could not be found

颤振代码

class CloudFunctionHandler {
  static Future<HttpsCallableResult> callCloudFunction({
    required String functionName,
    required Map<String, dynamic> parameters,
    bool isLocal = false,
  }) async {
    HttpsCallable callable;
    if (isLocal) {
      // FirebaseFunctions.instanceFor(
      //         region: "europe-west3") // NOTE Already try this
      //     .useFunctionsEmulator('http://127.0.0.1', 5001);
      FirebaseFunctions.instance.useFunctionsEmulator('http://127.0.0.1', 5001);

      callable = FirebaseFunctions.instance
          .httpsCallable(functionName, options: HttpsCallableOptions());
    } else {
      callable = FirebaseFunctions.instanceFor(region: "europe-west3")
          .httpsCallable(functionName, options: HttpsCallableOptions());
    }

    try {
      HttpsCallableResult result = await callable.call(parameters);
      return result;
    } on FirebaseFunctionsException catch (e) {
      print(e.message);
      throw CustomException(
        message: e.message,
        code: e.code,
      );
    } catch (e) {
      if (e is PlatformException) {
        final error = e as PlatformException;

        throw CustomException(
          message: error.details["message"] as String,
          code: error.details["code"] as String,
        );
      } else {
        throw CustomException(
          message: "Un erreur est survenue",
          code: e.toString(),
        );
      }
    }
  }
}

Firebase.json


{
  "functions": {},
  "emulators": {
    "functions": {
      "port": 5001
    },
    "firestore": {
      "port": 8080
    },
    "ui": {
      "enabled": true
    }
  }
}

它会来自网址吗?还要知道我在 IOS 模拟器上测试,并且我已经在 info.plist 中添加了 NSAllowsLocalNetworking 和 NSAllowsArbitraryLoads

标签: firebasefluttergoogle-cloud-functionsfirebase-tools

解决方案


错误的原因是:

exports.create = functions.https
  .region("europe-west3") <--- This line
  .onCall(async (data, context) => {
    userProfilDatabase.create(data, context.auth.uid);
  });

我以前的项目中从来没有遇到过这个问题,所以我找到了一个临时解决方案,可以用模拟器进行测试。我.region("europe-west3")在模拟器上进行本地评论,以便建立连接。这可能与我现在使用最新版本的packacge cloud_functions(^ 3.0.4)有关,因为以前的版本没有问题。

这当然是一个临时解决方案,我很乐意测试和验证任何其他更永久的提案。


推荐阅读