" No' Access-Control-Allow-Origin'标头出现在请求的资源上#34;错误,即使给出了正确的标题

时间:2018-03-08 08:06:01

标签: php reactjs cors

我正在尝试使用后端的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上运行。 提前谢谢。

1 个答案:

答案 0 :(得分:0)

为什么在需要执行以下操作时需要PHP服务器?

fetch("https://restcountries.eu/rest/v2/name/"+ this.state.countrystring,{
    method:'get', .... )

我通过Chrome控制台&amp; restcountries.eu支持CORS请求,所以这应该没问题