【问题标题】:How to set http or https based on window.location.protocol如何根据 window.location.protocol 设置 http 或 https
【发布时间】:2021-12-11 06:50:10
【问题描述】:

我正在开发一个颤振的 Web 应用程序。我想防止我的 API 端点在 https:// 或 http:// 上运行时出现 CORS 错误 如何修改下面的端点类以根据当前的window.location.protocol? 这是我的服务类:

import 'package:universal_html/html.dart';

class ApiEndPoint {
  Location currentLocation = window.location;
  static
  const host = 'api.xyz.com';
  static
  const http = 'http://';
  static
  const https = 'https://';
  static String baseUrl = "";
  // get base {
  //   if (currentLocation.protocol == 'https') {
  //     return baseUrl = "$https$host/api";
  //   } else if (currentLocation.protocol == 'http') {
  //     return baseUrl = "$http$host/api";
  //   }
  // }
}

【问题讨论】:

    标签: api dart flutter-web window.location


    【解决方案1】:

    我不确定我是否理解您的问题:

    1. 如果currentLocation.host != apihost(例如currentLocation 可能是https://app.xyz.com),您无论如何都必须在您的API 主机上允许CORS。为什么仍然支持您的 API 的不安全 http:// 协议。从不安全的网站访问https:// 资源没有问题。始终使用https://api.xyz.com 并允许CORS 来源http://app.xyz.comhttps://app.xyz.com

    2. 如果 currentLocation.host == apihost 只需从您的 apirequests 中删除 protocol://host 部分,只需访问 /api/...。浏览器(resp. webview)无论如何都会添加正确的协议和主机...

    除此之外,您目前的方法有什么问题?它应该工作。但是您可能可以将其简化为

    get base {
      return baseUrl = "${currentLocation.protocol}$host/api"
    }
    

    并放弃 const static httpconst static https 字符串常量。

    我对 Flutter 应用架构没有任何经验,也不知道您的应用的架构。所以我不知道是否有可能有多个ApiEndPoint 的实例与不同的window.locations。这可能会导致您的static String baseUrl 出现问题,因为static 变量在类的所有实例之间共享。所以当你同时有不同的window.locations 时,这将是不一致的。所以也许你应该完全放弃baseUrl 变量,然后做

    get base {
      return "${currentLocation.protocol}$host/api"
    }
    

    因为这将始终具有当前实例位置的正确协议。

    编辑关于您的评论:

    当然,您不能以静态方式访问base 属性。即ApiEndPoint.base 不起作用,因为base 不是static property。所以原则上你有两个选择(取决于你的架构)

    1. base(当然还有currentLocation)更改为static。然后你可以通过ApiEndPoint.base访问它

       static Location currentLocation = window.location;
       static get base {
         return "${currentLocation.protocol}$host/api"
       }
      
    2. 创建ApiEndPoint 类的实例,并仅通过该实例访问base 属性

       final api = ApiEndPoint();
       ...
       final baseUrl = api.base;
      

    无论如何,你应该阅读static关键字...

    【讨论】:

    • 问题在于您的实现和我的实现,同时尝试从我的服务类访问基本变量我收到错误“无法使用静态访问访问实例成员'base'”即当我尝试按如下方式分配基数 final baseUrl = ApiEndPoint.base;到 baseUrl 变量。那我怎样才能访问这个基值呢?
    • 查看更新的答案
    • 好的我研究一下static关键字的使用
    猜你喜欢
    • 1970-01-01
    • 2023-04-04
    • 2021-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 2011-06-29
    • 1970-01-01
    相关资源
    最近更新 更多