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
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.try adding this line to the headers of your response from the backend