我尝试从服务器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对象。
答案 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
获取