我正在尝试使用后端的PHP和前端的React JS读取一个rest api。
这是我的php代码:
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET');
header("Access-Control-Allow-Headers: X-Requested-With");
header('Content-Type: application/json');
$countryName = $_GET['countrystring'];
if (!empty($countryName)) {
$countryDataUrl =
'https://restcountries.eu/rest/v2/name/'.urlencode($countryName);
$countryDataJSON = file_get_contents($countryDataUrl);
$countryDataPHPArray = json_decode($countryDataJSON,true);
array_multisort($countryDataPHPArray);
$countryDataArrayLimited = array_slice($countryDataPHPArray, 0, 50);
echo json_encode($countryDataArrayLimited);
}
我尝试修改标题(' Access-Control-Allow-Origin:*'); 到标题(' Access-Control-Allow -Origin:http://localhost:3000');
我的React代码如下:
import React, { Component } from 'react';
class Countrycomponent extends Component {
constructor(props) {
super(props);
this.state = {countrystring: this.props.countrystring,countries:[]};
}
componentDidMount(){
console.log("Enter");
fetch("http://localhost:8000/?countrystring="+ this.state.countrystring,{
method:'get',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
}).
then(response=>response.json()).
then(responseData=>{console.log(responseData)})
}
render() {
return (
<div className="">
<p>hello</p>
{this.state.countries.name}
</div>
);
}
}
export default Countrycomponent;
我的反应在端口3000上运行,而php在端口8000上运行。 提前谢谢。
答案 0 :(得分:0)
为什么在需要执行以下操作时需要PHP服务器?
fetch("https://restcountries.eu/rest/v2/name/"+ this.state.countrystring,{
method:'get', .... )
我通过Chrome控制台&amp; restcountries.eu支持CORS请求,所以这应该没问题