You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Flutter Dio触发XMLHttpRequest onError回调的网络问题求助

解决Dio请求触发XMLHttpRequest onError连接错误的方案

结合你的代码、报错信息,以及你确认后端正常、已执行flutter clean的前提,可尝试以下排查方向:

1. 优先检查跨域配置(Web环境专属)

这个报错在Flutter Web场景下最常见,源于浏览器同源策略限制——即使后端API正常,若未配置允许当前Web应用域名的跨域请求,浏览器会直接拦截请求触发XMLHttpRequest错误:

  • 确认后端是否返回Access-Control-Allow-Origin响应头,值需包含你的Web应用域名(可临时设为*测试)
  • 若后端用Nginx代理,需在Nginx配置中添加跨域header:
    add_header Access-Control-Allow-Origin *;
    add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
    add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
    

2. 校验请求地址与协议

  • 你当前使用http协议,若Web应用部署在https环境,浏览器会拦截非安全请求,建议切换为https(需后端支持)
  • 直接在浏览器/Postman中调用该API,确认地址无拼写错误且能正常返回结果

3. 配置Dio的Web适配参数

给Dio添加Web环境专属配置,调整请求头或跨域相关参数:

import 'package:flutter/foundation.dart';
import 'package:dio/dio.dart';

// ...

Dio dio = Dio();
if (kIsWeb) {
  dio.options.withCredentials = true;
  dio.options.headers['Content-Type'] = 'application/json';
}
var response = await dio.post(
  "http://test.worldstreet.cn/service/account/verificationCode/send",
  data: { 
    "phoneRegion": _phoneRegion, 
    "phoneNumber": _phoneNumber, 
    "action": "$_action" 
  }
);

4. 排查本地网络与代理干扰

  • 关闭本地代理工具(如VPN、Charles)后重试,避免代理拦截请求
  • 切换网络环境(如WiFi换手机热点),排除本地防火墙限制

5. 升级Dio版本

旧版Dio在Web环境下可能存在XMLHttpRequest兼容问题,更新至最新版:
修改pubspec.yaml:

dependencies:
  dio: ^5.4.0+1 # 替换为pub上的最新版本

执行flutter pub get完成更新


内容的提问来源于stack exchange,提问作者Seaky Lone

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 23:13:16