Google Cloud Functions:返回有效的JSON [英] Google Cloud Functions: Return valid JSON

查看:79
本文介绍了Google Cloud Functions:返回有效的JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用cloud_functions软件包从Flutter应用中调用Google Cloud Function.

这是我的云功能:

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

这是我调用方法的flutter方法:

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

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

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

我的问题: 每次调用Cloud Function都会导致CloudFunctionsException.原因:"响应无效的JSON对象.".

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

预先感谢, 迈克尔

解决方案

如果要使用Flutter SDK调用可调用函数,则需要实际定义一个可调用函数.现在,您要声明一个HTTP函数,这是不一样的.请阅读可调用函数的文档,以了解如何声明和实现可调用函数. >

代替此:

functions.https.onRequest(...)

它看起来像这样:

functions.https.onCall(...)

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

I´m trying to call a Google Cloud Function from my Flutter App using the cloud_functions package.

This is my Cloud Function:

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

And this is my flutter method that calls this function:

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

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

As you can see it´s the most simply form of a request without any params.

My problem: Each call to the Cloud Function results in a CloudFunctionsException. Reason: "Response is not valid JSON object.".

Maybe somebody has an idea what´s going wrong here? If I call the cloud function via Postman or a browser, a valid JSON Object is returned and no exception is thrown.

Thanks in advance, Michael

解决方案

If you want to use the Flutter SDK to invoke a callable function, you need to actually define a callable function. Right now, you're declaring an HTTP function, which is not the same. Please read the documentation for callable functions to learn how to declare and implement a callable.

Instead of this:

functions.https.onRequest(...)

It will look like this:

functions.https.onCall(...)

Then, you return a JavaScript object to convert to JSON, rather than using a response object.

这篇关于Google Cloud Functions:返回有效的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆