flutter http POST到google cloud函数总是返回415

izkcnapc  于 2023-05-01  发布在  Flutter
关注(0)|答案(2)|浏览(121)

我尝试使用POST从Flutter调用Google Cloud函数,但它总是返回415。
这是电话:

http
        .post(
      Uri.parse('https://example.com/function'),
      headers: <String, String>{
        'content-type': 'application/json'
      },
      body: jsonEncode(<String, String>{
        "message": "test",
        "version": "1",
      }),
      encoding: Encoding.getByName('utf-8'),
    )

谷歌云函数设置正确,我可以用curl成功调用它

curl -X POST https://example.com/function --data '{"message": "test", "version": 1}' -H "Content-Type: application/json"

编辑:这是Google Cloud的功能:

import functions_framework

# Register an HTTP function with the Functions Framework
@functions_framework.http
def my_http_function(request):
    # Your code here

    print(request)

    # Return an HTTP response
    return "OK"

它是这样部署的:

gcloud functions deploy example-func \
--gen2 \
--runtime=python311 \
--region europe-west3 \
--source=. \
--entry-point=my_http_function \
--trigger-http \
--allow-unauthenticated

随着curl职位的工作,该功能似乎工作得很好,正如预期的。
编辑二:
这是由Flutter Web引起的。我发现了一些提示,CORS可能是问题所在,将Access-Control-Allow-Origin: *添加到头部可以解决它,但它没有。
有什么问题吗?

x8goxv8g

x8goxv8g1#

你应该发送json并在头中接受json:

headers: {
  "Content-Type": "application/json; charset=UTF-8",
  "Accept":"application/json",
},

更新:CORS

Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE
Access-Control-Allow-Headers: Content-Type

参考文献:
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

toiithl6

toiithl62#

尝试以下操作:

http.post(
      Uri.parse('https://example.com/function'),
      headers: <String, String>{
        "Content-Type": "application/json",
        "Accept": "application/json"
      },
      body: {
        "message": "test",
        "version": "1",
      },
    )

相关问题