I am working on a flutter web application.I want to prevent the CORS error whether my API Endpoint runs on https:// or http:// How can I modify my EndPoint Class below to set http or https based on the current window.location.protocol? Here is my service class:
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";
// }
// }
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
I'm not sure I understand your problem:
If
currentLocation.host != apihost(for instancecurrentLocationcould behttps://app.xyz.com) you'll have to allow CORS on your API host anyways. Why then still support unsecurehttp://protocol for your API. It's no problem to accesshttps://resources from an unsecured website. Just always usehttps://api.xyz.comand allow CORS originshttp://app.xyz.comandhttps://app.xyz.comIf
currentLocation.host == apihostjust ditch theprotocol://hostpart from your apirequests and just access/api/.... The browser (resp. webview) will add the correct protocol and host anyways ...
Other than that, what's wrong with your current approach? It should work. But you could probably simplify it to
get base {
return baseUrl = "${currentLocation.protocol}$host/api"
}
and ditch the const static http and const static https string constants.
I don't have any experience with flutter app architecture, nor do I know the architecture of your app. So I don't know whether it's possible to have multiple instances of that ApiEndPoint with different window.locations. This will probably lead to a problem with your static String baseUrl, as a static variable is shared among all instances of a class. So when you have different window.locations at the same time, this will be inconsistent. So maybe you should ditch the baseUrl variable alltogether and just do
get base {
return "${currentLocation.protocol}$host/api"
}
as this will always have the correct protocol for the location of the current instance.
EDIT Regarding your comment:
Of course you cannot access the base property in a static way. Ie ApiEndPoint.base won't work, because base is not a static property. So in principle you have 2 options (depending on your architecture)
Change
base(and of course alsocurrentLocation) to bestatic. Then you can access it vieApiEndPoint.basestatic Location currentLocation = window.location; static get base { return "${currentLocation.protocol}$host/api" }Create an instance of your
ApiEndPointclass, and access thebaseproperty only via that instancefinal api = ApiEndPoint(); ... final baseUrl = api.base;
In any case, you should read about static keyword ...
