3

I am trying to make an HTTP request 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 adding 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
  • 1
    Question was framed nicely. Before coming through this question, I thought it was some issue with flutter packages. This question motivated me to make changes in my backend. Commented Mar 16, 2021 at 15:24

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

flask-cors.readthedocs.io/en/latest . I used this when I was using flask as the server
User the cors npm package to achieve this on node or express server. Link for package : npmjs.com/package/cors . You can use this as a middleware by doing :const cors = require("cors"); app.use(cors())
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.