18
votes

I was trying my hands on flutter web. I tried to connect a simple flutter web app I created to mysql database and localhost using the http package. However I dont get any data returned from the request method. When I tried to print out snaphot.error I got this: XMLHttpRequest error. I have this method in a FutureBuilder()

getMethod()async{
  String theUrl = 'https://localhost/fetchData.php';
  var res = await http.get(Uri.encodeFull(theUrl),headers: {"Accept":"application/json"});
  var responsBody = json.decode(res.body);
  print(responsBody);
  return responsBody;

}
3
Have you tried this request on you web browser or maybe postman? lets see the result - JideGuru
Did you find any solution? I have asked the same question here: stackoverflow.com/questions/57340929/… - Stecco
I also faced this issue, i changed CORS policy from Back end then it work like charm!! - Hardik Bhalala
Hello @HardikBhalala what changes you made in Backend? - Nehang Patel

3 Answers

7
votes

You can also Add the code below to your php file like so:

<?php
require('connection.php');
header("Access-Control-Allow-Origin: *");
....
code goes here
....
?>

I Tried this on LocalHost and it worked.

NB: If you're using nodejs install the cors() package and use like

var express = require('express')
var app = express()
var cors = require('cors')

app.use(cors())

Check out the CORS package on npmjs

3
votes

I literally just stumbled over the error myself. You are falling afoul of CORS... if you trace the underlying network traffic, you should see that it sends an OPTIONS request first.

To get it to "work" temporarily, you can launch Chrome with CORS turned off. Obviously, this is not a long term solution, but it should get you going. The command you need is:

open /Applications/Google\ Chrome.app --args --disable-web-security --user-data-dir
1
votes

What I found out and solved the issue is

For Accessing a website made by flutter basically you are calling a JS script

and for any website to give access to a script (which in my case was another website I was accessing the api from ) you need to give some sort of clearance to access

Which is in this case is CORS - Cross-Origin Resource Sharing

Add below code to your websites .htaccess file

<ifModule mod_headers.c>
    SetEnvIf Origin "http(s)?://(www.)?(localhost:55538|somedomain.com)$" AccessControlAllowOrigin=$0
    Header add Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
    Header always set Access-Control-Allow-Methods: "GET,POST,PUT,DELETE,OPTIONS"
</ifModule>    

adding this will now grant access to your flutter website to hit requests to your apis