【问题标题】:how to fix flutter web http error making http request to a particular web server如何修复向特定Web服务器发出http请求的flutter web http错误
【发布时间】:2019-10-06 02:58:00
【问题描述】:

我正在尝试在我的 Flutter Web 应用程序中向 000webhost 发出 HTTP 请求,如下所示。第一种方法和第二种方法一样,我只是改变了网址。但是,第一个有效,但第二个无效。有人建议添加更多标题,但我不知道要添加哪些标题。

// 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; 
}

【问题讨论】:

  • 问题的框架很好。在回答这个问题之前,我认为这是颤振包的一些问题。这个问题促使我对后端进行更改。

标签: dart flutter flutter-web hummingbird


【解决方案1】:

在为此苦苦挣扎了一段时间后,我发现问题出在服务器端 我必须在 000webhost 上将 Header add Access-Control-Allow-Origin "*" 添加到 .htaccess 这为我解决了这个问题

【讨论】:

  • flask-cors.readthedocs.io/en/latest 。我在使用flask作为服务器时使用了这个
  • 使用 cors npm 包在 node 或 express 服务器上实现这一点。包链接:npmjs.com/package/cors。您可以通过执行 :const cors = require("cors"); 将其用作中间件; app.use(cors())
【解决方案2】:

您也可以像这样将下面的代码添加到您的 php 文件中:

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

我在 LocalHost 上试过了,效果很好

【讨论】:

    猜你喜欢
    • 2021-01-27
    • 2019-10-02
    • 2017-05-19
    • 2019-07-09
    • 1970-01-01
    • 2019-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多