无法在React中从我的API服务器获取数据

时间:2020-03-01 17:49:34

标签: php reactjs rest api

我尝试从服务器https://www.my-site.com/api中获取数据(文件夹中的文件列表),其中我有index.php个文件

<?php
    header("Access-Control-Allow-Origin: *");
    header("Content-Type: application/json");

    $dir = "./photos"; //path

    $list = array(); //main array

    if(is_dir($dir)){
        if($dh = opendir($dir)){
            while(($file = readdir($dh)) != false){

                if($file == "." or $file == ".."){
                    //...
                } else {
                    $list3 = array(
                        'url' => $file);
                        array_push($list, $list3);
                }
            }
        }

        $return_array = array('photos'=> $list);

        echo json_encode($return_array);
    }
?>

在我的React应用中,我尝试使用fetch

fetch('https://www.my-site.com/api', {
   method: 'GET',
   redirect: 'follow',
   headers: {
  }
})
  .then(response => response.json())
  .then(res => console.log(res))
  .catch(error => console.log('error', error));

,但结果为CORS request did not succeedCORS header 'Access-Control-Allow-Origin' missing。当我使用Postman时,一切正常,并且我得到了带有所需数据的json对象。

2 个答案:

答案 0 :(得分:0)

尝试添加:

Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"

.htaccess文件

答案 1 :(得分:0)

问题解决了。

我尝试从my-site.com/api获取数据,但我应该从my-site.com/api/index.php获取