【发布时间】:2020-06-14 02:36:48
【问题描述】:
我尝试从我的服务器 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 succeed 和CORS header 'Access-Control-Allow-Origin' missing。当我使用 Postman 时,一切都很好,我得到了带有我想要的数据的 json 对象。
【问题讨论】:
-
您应该检查您的响应标头。例如,请参阅stackoverflow.com/questions/20189756/…。