我正在開發一個顫振 Web 應用程式。無論我的 API 端點是在 https:// 還是 http:// 上運行,我都想防止 CORS 錯誤如何修改下面的端點類以根據當前視窗設定 http 或 https。位置協議?這是我的服務類:
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";
// }
// }
}
uj5u.com熱心網友回復:
我不確定我是否理解您的問題:
如果
currentLocation.host != apihost(例如currentLocation可能是https://app.xyz.com)您無論如何都必須在您的 API 主機上允許 CORS。為什么還要http://為您的 API支持不安全的協議。https://從不安全的網站訪問資源沒有問題。只要始終使用https://api.xyz.com并允許 CORS 起源http://app.xyz.com和https://app.xyz.com如果
currentLocation.host == apihost只是protocol://host從您的 apirequests 中洗掉該部分并訪問/api/.... 瀏覽器(resp. webview)無論如何都會添加正確的協議和主機......
除此之外,您目前的方法有什么問題?它應該作業。但你可以把它簡化為
get base {
return baseUrl = "${currentLocation.protocol}$host/api"
}
并丟棄const static http和const static https字串常量。
我對 Flutter 應用程式架構沒有任何經驗,也不了解您的應用程式架構。所以我不知道是否有可能有多個ApiEndPoint不同的window.locations. 這可能會導致您的 出現問題static String baseUrl,因為static變數在類的所有實體之間共享。所以當你同時有不同的window.locations 時,這將是不一致的。所以也許你應該完全拋棄baseUrl變數,然后做
get base {
return "${currentLocation.protocol}$host/api"
}
因為這將始終具有當前實體位置的正確協議。
編輯關于您的評論:
當然,您不能base以靜態方式訪問該屬性。即ApiEndPoint.base不會作業,因為base不是靜態屬性。所以原則上你有 2 個選項(取決于你的架構)
更改
base(當然也currentLocation)為static. 然后你可以訪問它 vieApiEndPoint.basestatic Location currentLocation = window.location; static get base { return "${currentLocation.protocol}$host/api" }創建您的
ApiEndPoint類的實體,并base僅通過該實體訪問該屬性final api = ApiEndPoint(); ... final baseUrl = api.base;
無論如何,您應該閱讀有關static關鍵字...
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/336588.html
上一篇:Thymeaf計算出的URL值
下一篇:使用獲取的API專案填充下拉串列
