如何从Python云函数在Flutter Web中成功发出http请求?

问题描述 投票:0回答:1

我有一个非常基本的Python云函数(启用了CORS),看起来像:

@functions_framework.http
def function_with_cors_enabled(event):
    method = event.method
    endpoint = event.path
    route_key = method + " " + endpoint
    logging.info(f"Route key : {route_key}")
    if method == "OPTIONS":
        # Allows GET requests from any origin with the Content-Type
        # header and caches preflight response for an 3600s
        headers = {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'POST, GET',
            'Access-Control-Allow-Headers': 'Content-Type, X-AppCheck',
            'Access-Control-Max-Age': '3600'
        }
        return '', 204, headers

    # Set CORS headers for the main request
    headers = {
        'Access-Control-Allow-Origin': '*',
    }
    if route_key == "GET /test":
        return test_call(), 200, headers
    return {"error": "not allowed"}, 401

def test_call():
    logging.info("Test !")
    return {"message", "success"}

我已经尝试了所有返回组合:

  • return test_call(), 200, headers
    文档
  • 匹配
  • return test_call(), headers
    ,其中
    test_call()
    除了
    dict
  • 之外还返回状态代码
  • return test_call()
    没有
    headers
  • 等等...

当我检查我的云日志记录时,我确实看到一切都在 python 中成功运行,

Test !
日志的返回状态代码为 200。

在 Flutter web 中我确实看到了一个未定义的错误:

ClientException: XMLHttpRequest error., uri=https://mycloud_function_endpoint

如何从Python云函数在flutter web中成功发出http请求?

python flutter google-cloud-functions
1个回答
0
投票

我必须简单地添加:

headers = event.headers
位于函数顶部:

@functions_framework.http
def function_with_cors_enabled(event):
    method = event.method
    endpoint = event.path
    headers = event.headers # this line
    route_key = method + " " + endpoint
    logging.info(f"Route key : {route_key}")
    if method == "OPTIONS":
        # Allows GET requests from any origin with the Content-Type
        # header and caches preflight response for an 3600s
        headers = {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'POST, GET',
            'Access-Control-Allow-Headers': 'Content-Type, X-AppCheck',
            'Access-Control-Max-Age': '3600'
        }
        return '', 204, headers

    # Set CORS headers for the main request
    headers = {
        'Access-Control-Allow-Origin': '*',
    }
    if route_key == "GET /test":
        return test_call(), 200, headers
    return {"error": "not allowed"}, 401

这意味着除了我在此处添加的标头之外,flutter web 还期望函数中包含一些标头。

© www.soinside.com 2019 - 2024. All rights reserved.