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

Flutter Web如何基于window.location.protocol设置API的http/https协议

Flutter Web 动态适配API协议实现方案

核心问题修复点

  • 原代码中currentLocation为实例属性,静态逻辑无法直接调用,需改为静态变量
  • window.location.protocol返回值自带冒号(格式为http:/https:),原有判断条件和实际返回值不匹配,会导致逻辑失效
  • 建议将baseUrl封装为静态getter,每次调用时动态读取当前页面协议生成对应接口前缀,不需要提前赋值存储

修改后完整代码

import 'package:universal_html/html.dart';

class ApiEndPoint {
  static final Location currentLocation = window.location;
  static const host = 'api.xyz.com';
  static const httpPrefix = 'http://';
  static const httpsPrefix = 'https://';
  
  // 动态生成对应协议的接口基础地址
  static String get baseUrl {
    if (currentLocation.protocol == 'https:') {
      return "$httpsPrefix$host/api";
    }
    // 所有非https场景默认用http,可根据需求调整默认值
    return "$httpPrefix$host/api";
  }
}

补充说明

  • 上述配置仅解决API协议和前端页面协议不一致导致的CORS报错,你仍需要在API服务端配置跨域规则,允许你的Flutter Web部署域名的访问请求,否则依然会触发CORS拦截
  • 本地开发阶段可以直接使用Flutter Web的代理配置转发API请求,完全规避开发环境的CORS问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 15:45:07