0

I'm using time API in my flutter application through http package :

 var url = Uri.parse(
          'https://www.timeapi.io/api/Time/current/zone?timeZone=Europe/Italy');
      var responseDateTime = await http.get(secondUrl, headers: {
        "Accept": "application/json",
        "Access-Control-Allow-Origin": "*"
      });

      var responseDateTimeBody =
          jsonDecode(responseDateTime.body) as Map<String, dynamic>;

this method works well on android and I can read json response in my app however I've got this XMLHttpRequest error. after migrate to flutter web , how can I solve this ?

I've already read these responses to fix XMLHttpRequest error on flutter web:

Dart/Flutter: Http request raises XMLHttpRequest error

How to solve flutter web api cors error only with dart code?

and my error was fixed locally using these suggestions; however, it persists in the production app; how do I fix it for the final product?

Behnam
  • 329
  • 5
  • 15
  • Adding CORS headers to the request will make NO difference at all. The headers need to be added by the server, which apparently timeapi.io does not. You would have to proxy through your own backend. Similar answer here: https://stackoverflow.com/questions/72250589/how-to-use-timeapi-io-api-with-js – Richard Heap Jun 02 '22 at 20:44
  • @RichardHeap You mean we can't use external APIs within the flutter project because of CORS issues? So, what should we do? This is a significant disadvantage.I'm using Parse Platform as backend how can I proxy api call through this backend – Behnam Jun 02 '22 at 21:24
  • You can't use external APIs in any web application that uses XMLHttpRequest where the server doesn't allow it by adding the correct CORS headers. This IS the design of CORS, which says "HTTP-header based mechanism that allows a **server** to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading resources." (my emphasis) – Richard Heap Jun 02 '22 at 21:51
  • To proxy, you just make the same (or similar) API call to your server, which then requests data from the remote API. Having fetched that data back to the server, the server formats it (could leave it the same of course) and responds to the original request. Your server should add CORS headers during debugging, but eventually, if you host you flutter web app from the same server, no CORS headers would be needed as the Flutter web app will simply be calling back to its serving host. – Richard Heap Jun 02 '22 at 21:54

0 Answers0