How to make HTTP request to In Flutter Web

不想你离开。 提交于 2021-01-18 08:01:47

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!