how to fix flutter web http error making http request to a particalar web server

时光怂恿深爱的人放手 提交于 2020-06-17 09:34:04

问题


I am trying to make an http requset to 000webhost as below in my flutter web app. The first method is the same as the second,I only changed the url. However the first one works but the second does not work. someone suggested to add more headers but I have no idea which headers to add.

/// This method WORKS getMethod()async{

  print("IN GET ....");
  String theUrl = 'https://jsonplaceholder.typicode.com/todos';
  var res = await http.Client().get(Uri.encodeFull(theUrl),headers: {"Accept":"application/json"});
  //var res = await http.get(Uri.encodeFull(theUrl),headers: {"Accept":"application/json"});
  var responsBody = json.decode(res.body);
  print(responsBody);
  return responsBody;

}

//// this DOES NOT WORK

getMethod()async{

  print("IN GET ....");
  String theUrl = 'https://funholidayshotels.000webhostapp.com/fetchData.php';
  var res = await http.Client().get(Uri.encodeFull(theUrl),headers: {"Accept":"application/json"});
  //var res = await http.get(Uri.encodeFull(theUrl),headers: {"Accept":"application/json"});
  var responsBody = json.decode(res.body);
  print(responsBody);
  return responsBody;

}

回答1:


After struggling with this for some time I figured out the problem was from the server side I had to add Header add Access-Control-Allow-Origin "*" to .htaccess on 000webhost And This solves it for me




回答2:


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



来源:https://stackoverflow.com/questions/56209073/how-to-fix-flutter-web-http-error-making-http-request-to-a-particalar-web-server

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