Flutter如何支持浏览器跨域

当使用 flutter 构建 web 项目,直接运行在 chrome 浏览器发出网络请求会发生跨域错误 strict-origin-when-cross-origin(CROS),比如在 dart 代码直接用 dio.get("https://www.yunfuit.com"),dio 会报错,在 chrome 的 DevTools 中会发现 CROS 错误。

解决办法:

  • flutter\bin\cache删除flutter_tools.stamp
  • flutter\packages\flutter_tools\lib\src\web下打开chrome.dart,并在--disable-extensions下新增--disable-web-security。详细如下:

final List<String> args = <String>[
      chromeExecutable,
      // Using a tmp directory ensures that a new instance of chrome launches
      // allowing for the remote debug port to be enabled.
      '--user-data-dir=${userDataDir.path}',
      '--remote-debugging-port=$port',
      // When the DevTools has focus we don't want to slow down the application.
      '--disable-background-timer-throttling',
      // Since we are using a temp profile, disable features that slow the
      // Chrome launch.
      '--disable-extensions',
      '--disable-web-security',
      '--disable-popup-blocking',
      '--bwsi',
      '--no-first-run',
      '--no-default-browser-check',
      '--disable-default-apps',
      '--disable-translate',
      if (headless)
        ...<String>[
          '--headless',
          '--disable-gpu',
          '--no-sandbox',
          '--window-size=2400,1800',
        ],
      ...webBrowserFlags,
      url,
    ];

然后重启编译器(VS Code / Android Studio),重新运行即可成功!

推荐一个非常好用的chatgpt,微信扫码:

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值