我试图在我的Flutter Web应用程序中向000webhost提出HTTP请求。第一个方法与第二种方法相同,我只更改了URL。但是,第一个起作用,但第二个不起作用。有人建议添加更多标头,但我不知道要添加哪个标题。
// 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;
}
在努力挣扎一段时间后,我弄清楚问题是从服务器端我不得不将 Header add Access-Control-Allow-Origin "*"
添加到000webhost上的 .htaccess
,这为我解决了
您也可以将下面的代码添加到php文件中:
<?php
require('connection.php');
header("Access-Control-Allow-Origin: *");
....
code goes here
....
?>
我在local主机上尝试了此操作,它起作用