简体   繁体   中英

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

I am trying to read a rest api using php in the backend and React JS in the front end.

Here is my php code:

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

I have tried modifying header('Access-Control-Allow-Origin: *'); to header('Access-Control-Allow-Origin: http://localhost:3000 ');

My React code goes as follows:

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;

My react is running on port 3000 and the php on port 8000. Thanks in advance.

Why do you need a PHP server when you can just do the following instead?

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

I tested by making a request from Chrome console & restcountries.eu supports CORS request, so this should be fine

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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