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.

2 Answers 2

4

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

<?php

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

?>
Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

Even using HTML renderer doesn't work. Still getting the same error..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.