问题
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;
}
回答1:
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
回答2:
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
回答3:
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
来源:https://stackoverflow.com/questions/56139505/how-to-make-http-request-to-in-flutter-web