我有一个非常基本的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请求?
我必须简单地添加:
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 还期望函数中包含一些标头。