1

I'm working on a simple project with Flutter web. When I try any API Call on my back-end I'm getting an error like 'Error: XMLHttpRequest error.' I did some research and found out that it is related to CORS.

This is the final version of my code in PHP.

<?php

header("access-control-allow-origin: *");

require_once("connect.php");
$result = $db->query("SELECT * FROM feedback ORDER BY id DESC") -> fetchAll();

echo json_encode($result);  

?>

My Flutter code for making API call

List? feedbackList;

  getFeedbacks() async {
    var url = Uri.parse('myDomainUrl/get.php');
    var response = await http.get(url);
    print('RESPONSE REPONSE RESPONSE RESPONSE: ${response.statusCode}');

    if (response.statusCode == 200) {
      setState(() {
        feedbackList = json.decode(response.body);
      });
      return feedbackList;
    }
  }

It works on mobile but somehow I'm still getting same error on Web.

Emre
  • 111
  • 2
  • 10

2 Answers2

3

try adding this line to the headers of your response from the backend

<?php

header('access-control-allow-origin: *');
header('Access-Control-Allow-Headers: *');
...

?>
AceP
  • 112
  • 1
  • 12
1

CORS is an issue exclusive to browsers, and not mobile apps. This is why it works fine on mobile. Check out this answer to perhaps fix your CORS issue in PHP.

If you can't solve it, you can build your web app using html renderer instead of canvas kit.

Huthaifa Muayyad
  • 11,321
  • 3
  • 17
  • 49