[英]Can't fetch data from my API server in React
I try to fetch data (list of files in folder) from my server https://www.my-site.com/api
where I've got index.php
file which is我尝试从我的服务器
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);
}
?>
and in my React app i try to use fetch
在我的 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));
but the result is CORS request did not succeed
and CORS header 'Access-Control-Allow-Origin' missing
.但结果是
CORS request did not succeed
并且CORS header 'Access-Control-Allow-Origin' missing
。 When im using Postman, everything it's ok, and I get json object with data I wanted.当我使用 Postman 时,一切都很好,我得到了带有我想要的数据的 json 对象。
Try to add :尝试添加:
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"
To .htaccess
file到
.htaccess
文件
Problem solved.问题解决了。
I tryed to fetch data from my-site.com/api
but I should fetch from my-site.com/api/index.php
我试图从
my-site.com/api
获取数据,但我应该从my-site.com/api/index.php
获取
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.