【问题标题】:Google Cloud Functions: Return valid JSON谷歌云函数:返回有效的 JSON
【发布时间】:2019-06-01 01:48:36
【问题描述】:

我正在尝试使用 cloud_functions 包从我的 Flutter 应用中调用 Google Cloud Function。

这是我的云函数:

export const helloWorld = functions.region('europe-west1').https.onRequest((request, response) => {
response.status(200).json({
    message: "Hello World!"
  });
});

这是我调用这个函数的颤振方法:

try {
  final dynamic resp =
      await CloudFunctions.instance.call(
    functionName: "helloWorld"
  );
  print(resp);

} on CloudFunctionsException catch (e) {
  ...
} catch (e) {
  ...
} finally {
  ...
}

如您所见,这是最简单的请求形式,没有任何参数。

我的问题: 对 Cloud Function 的每次调用都会导致 CloudFunctionsException。原因:“响应不是有效的 JSON 对象。”。

也许有人知道这里出了什么问题?如果我通过 Postman 或浏览器调用云函数,则返回一个有效的 JSON 对象,并且不会抛出异常。

提前致谢, 迈克尔

【问题讨论】:

    标签: json flutter google-cloud-platform google-cloud-functions cloud


    【解决方案1】:

    如果要使用 Flutter SDK 调用可调用函数,则需要实际定义可调用函数。现在,您正在声明一个 HTTP 函数,这并不相同。请read the documentation for callable functions 了解如何声明和实现可调用对象。

    而不是这个:

    functions.https.onRequest(...)
    

    看起来像这样:

    functions.https.onCall(...)
    

    然后,您返回一个 JavaScript 对象以转换为 JSON,而不是使用响应对象。

    【讨论】:

    • 这正是我根据模块文档首先所做的 - 抛出相同的异常:export const helloWorld = functions.https.onCall((data, context) => { return { message: "Hello World" } });
    【解决方案2】:

    我可以找到错误: 一旦您定义了默认区域的另一个区域,flutter 包 cloud_functions 似乎无法再找到该功能:

    作品:

    export const helloWorld = functions.https.onCall((data, context) => {
        return {
            message: "Hello World"
        }
    });
    

    不起作用:

    export const helloWorld = functions.region('europe-west1').https.onCall((data, context) => {
        return {
            message: "Hello World"
        }
    });
    

    【讨论】:

    • 如果你改变了函数定义中的区域,你也改变了它的url。功能客户端 SDK 不知道您已完成此操作,因此您需要告诉它区域,以便它可以正确构建 URL。在 android 中,您使用getInstance(region) 更改区域。不知道在 Flutter 上是如何工作的,大概类似。
    • 目前这个包似乎不支持 - 我会在 GitHub 上推荐它。感谢您的投入!
    • 这里有同样的问题,你有没有得到关于这个@Michael 的任何更新?
    • 谢谢@Michael!拯救了我的夜晚!
    【解决方案3】:

    我遇到了同样的问题,对我有用的是:

    (添加到@Michael 的答案)

    声明调用云函数时,在这两种情况下都指定区域很重要。

    我的错误是我只在函数声明上设置了区域代码。

    更多:https://firebase.google.com/docs/functions/locations#client-side_location_selection_for_callable_functions

    对于 Flutter,您应该在单例 CloudFunctions 的 region 参数中指定区域:

    CloudFunctions(app: FirebaseApp.instance, region: "europe-west1")
    

    【讨论】:

      猜你喜欢
      • 2019-09-23
      • 1970-01-01
      • 2019-02-15
      • 2018-12-07
      • 2018-10-02
      • 2021-01-22
      • 2020-09-11
      • 2018-11-15
      • 1970-01-01
      相关资源
      最近更新 更多