Flutter Web调用Azure HTTP Trigger遇XMLHttpRequest错误求助
我目前用Flutter开发Web应用,用来查看Azure中的数据,通过Azure HTTP Trigger函数在Flutter Web应用发起请求后返回数据。已经创建了Azure HTTP Trigger并使用其URL建立连接,但运行以下代码时出现错误:
Future<void> main() async { // Construct the URL to fetch data from Azure function String url = "https://dashboardfunctionapp.azurewebsites.net/api/http_trigger?code=*************=="; try { // Make the HTTP GET request final response = await http.get( Uri.parse(url) // headers: { // 'Authorization': Key, // 'Content-Type': 'application/json', // }, ); // Check if the request was successful (status code 200) if (response.statusCode == 200) { // Parse the response body (data from Azure IoT Hub) String responseBody = response.body; print('Data from Azure IoT Hub: $responseBody'); // Process the data as needed // Example: Convert JSON data to Dart objects } else { // If the request was not successful, print the error print('Failed to fetch data from Azure IoT Hub. Error code: ${response.statusCode}'); } } catch (error) { // Catch any exceptions that occur during the HTTP request print('Error fetching data from Azure IoT Hub: $error'); } }
报错信息:
Error fetching data from Azure IoT Hub: ClientException: XMLHttpRequest error., uri=https://nodereddashboardfunctionapp.azurewebsites.net/api/http_trigger?code=************==
请问该问题的原因是什么?
CORS跨域限制:这是Flutter Web调用外部API最常见的问题。Azure Function默认不允许任意域名跨域请求,你的Flutter Web域名不在允许列表里,浏览器就会拦截请求,抛出XMLHttpRequest错误。
解决:登录Azure Portal,找到你的Function App,进入「CORS」配置页面,把Flutter Web的运行域名(本地调试一般是http://localhost:端口号,线上部署则填实际域名)添加到允许的Origins列表,保存设置即可。URL或函数密钥不匹配:注意到报错里的请求URL是
nodereddashboardfunctionapp.azurewebsites.net,但代码里写的是dashboardfunctionapp.azurewebsites.net,两个域名不一致,大概率是复制URL时出错了;另外也可能是函数密钥无效、过期或者输入错误。
解决:去Azure Function的「函数」页面,复制正确的HTTP Trigger URL和密钥,替换代码里的url字段,确保完全一致。Flutter Web HTTP客户端的浏览器限制:Flutter Web的
http包基于浏览器的XMLHttpRequest实现,部分场景下可能存在兼容性问题。
解决:可以尝试换用dio包发起请求,或者本地调试时指定端口和主机名,比如运行命令flutter run -d chrome --web-port=5000 --web-hostname=0.0.0.1,避免浏览器的同源策略限制。Azure Function未正常运行:如果函数本身部署失败、处于停止状态,或者触发逻辑有问题,也会导致请求失败。
解决:在Azure Portal的Function App页面,检查函数状态是否为运行中,并且通过「测试/运行」功能手动触发HTTP Trigger,确认能正常返回数据。
内容的提问来源于stack exchange,提问作者sai

