繁体   English   中英

即使给出了正确的标题,也不会出现“在请求的资源上没有'Access-Control-Allow-Origin'标头”错误

[英]“No 'Access-Control-Allow-Origin' header is present on the requested resource” error, even when proper headers are given

我正在尝试在后端使用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上运行。在此先感谢。

当您只需执行以下操作时,为什么需要PHP服务器?

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

我通过从Chrome控制台发出请求进行了测试,并且restcountries.eu支持CORS请求,因此应该可以

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM