如何在Flutter Web中成功调用Python云函数的HTTP请求?
问题描述
我有一个已开启CORS的基础Python云函数,代码如下:
@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()同时返回状态码和字典)return test_call()(不带headers)- 其他组合...
查看Cloud Logging日志,Python代码运行正常,能看到Test !日志且返回状态码为200,但在Flutter Web中出现错误:
ClientException: XMLHttpRequest error., uri=https://mycloud_function_endpoint
请问如何在Flutter Web中成功发起对Python云函数的HTTP请求?
解决方案
1. 修复云函数的返回格式错误
你的test_call()函数返回的是集合对象{"message", "success"},而非标准JSON格式的键值对字典{"message": "success"},这会导致云函数返回的内容无法被前端正确解析,进而触发XMLHttpRequest错误。
修改test_call()函数:
def test_call(): logging.info("Test !") return {"message": "success"} # 将逗号改为冒号,使用合法的JSON字典格式
2. 配置Flutter Web的请求参数
使用http包发起请求时,需确保请求头和方法匹配云函数的CORS规则:
示例GET请求代码
import 'package:http/http.dart' as http; Future<void> callCloudFunction() async { try { final response = await http.get( Uri.parse('https://mycloud_function_endpoint/test'), headers: { 'Content-Type': 'application/json', // 若需X-AppCheck验证,在此添加对应的头信息 }, ); if (response.statusCode == 200) { print('请求成功: ${response.body}'); // 可进一步解析JSON // final data = jsonDecode(response.body); } else { print('请求失败,状态码: ${response.statusCode}'); } } catch (e) { print('请求异常: $e'); } }
注意事项
- 若使用
dio包,同样要保证请求头包含Content-Type: application/json,且不添加云函数未允许的自定义头。 - 开发时避免使用浏览器隐私模式,防止影响CORS预请求缓存。
3. 验证云函数响应
通过浏览器开发者工具的Network面板,检查:
- 响应头是否包含
Access-Control-Allow-Origin: * - 响应体是否为合法的JSON格式
内容的提问来源于stack exchange,提问作者Tom3652
相关产品推荐
相关产品推荐

