简体   繁体   中英

URL blocked ( Access-Control-Allow-Origin - Missing Header) while I am trying to get the data from Bluehost to react website app

I am creating a website using (react for website) that I wanted to get the data from my server in blueHost using php as a backend and react (JavaScript) as front-end

I have an issue that I am not able to load the data case of my file.php has blocked because of Access control allow Origin

any idea how can solve this issue?

here is my code app.js (react)

    const getData = async () => {
    fetch(URL,{
      mode:'cors',
      headers : {
        'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8',
  'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Origin': 'http://localhost:3004',
    'Access-Control-Allow-Methods': 'GET',
    'Content-type': 'application/json; charset=UTF-8',
    'Access-Control-Allow-Headers':'Origin, X-Requested-With, Content-Type, Accept',
    'Access-Control-Request-Headers': 'x-token'
    }
    })
    .then((response) => response.json())
    .then((json) => console.log(json.flags))
    .catch((error) => console.log(error))
    .finally(() => console.log(false));

}

and here is my file.php

 <?php
include 'DBConfig.php';
 
$conn = new mysqli($HostName, $HostUser, $HostPass, $DatabaseName);
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, X-Requested-With");

$json = file_get_contents('php://input');
$obj = json_decode($json, true);

if ($conn->connect_error) {
 
 die("Connection failed: " . $conn->connect_error);
}
 
$sql = "SELECT * FROM `Transactions`";
 
$result = $conn->query($sql);
 
if ($result->num_rows >0) {
 
 
 while($row[] = $result->fetch_assoc()) {
 
 $tem = $row;
 
 $json = json_encode($tem);
 
 
 }
} else {
    $json = json_encode("false");

}
 echo $json;
$conn->close();
?>

any idea how can I solve this issue?

this error is because of run code in local. for fix this. you should add this extension in google chrome. (Allow CORS: Access-Control-Allow-Origin) then on and off.then on again and test your code.

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