来自 Flutter Web 的 HTTP Post 请求

HTTP Post request from Flutter Web

我在 Google Cloud Functions 上有一个函数,我正试图在我的 Flutter Web 应用程序中向其发出 post 请求。我在 Python 中测试了一个 post 请求,它适用于以下请求:

params = {'input_key':'input_value'}
headers = {"Content-Type": "application/json"}
r = requests.post("https://us-central1-lucid-bond-261904.cloudfunctions.net/cloudFunction", data=jason.dumps(params), headers=headers)

但是当我尝试使用 http 包从我的 Flutter Web 应用程序执行相同的请求时,我不断收到 XMLHttpRequest 错误。这是我的 flutter 网络应用程序中的 http 请求

String path = "https://us-central1-lucid-bond-261904.cloudfunctions.net/cloudFunction";
Map params = {'input_key':'input_value'}
var response = await http.post(path, body: json.encode(params), headers: <String, String>{'Content-Type': 'application/json'});

我知道它成功触发了云函数,因为我让云函数做的第一件事就是将 'hello' 打印到日志中。这似乎是我选择内容类型的方式的错误。 这意味着内容类型可能会更改为“application/json; charset=utf-8”,但他们指定的修复不适用于 Flutter Web,因为 dart io 包不不适用于 Flutter Web。 那么如何正确指定内容类型? 或者有没有更好的 flutter 包可以用于这种情况?

Flutter 中抛回的错误是:

Error: XMLHttpRequest error.
    C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 264:20      get current
packages/http/src/browser_client.dart 84:22

还有我的 Cloud Function 中的错误

line 99, in cloudFunction shop_name = inputs_dict['input_key'] TypeError: 'NoneType' object is not subscriptable

编辑: 刚刚尝试从 Postman 执行相同的 post 请求并且成功。尽管如此,我的 flutter 应用程序仍然无法正常工作。我需要在 Google Cloud Function 中启用 CORS 或其他功能吗?

我终于成功了。在我的云函数中,request.get_json() 返回空值。当我添加参数 force=True 时,它​​终于起作用了。通过 python 或邮递员触发功能时,我不必执行 force=True ,但由于某种原因,通过 flutter 触发它需要 force=true.

request.get_json(force=True)