【问题标题】:Can't fetch data from my API server in React无法在 React 中从我的 API 服务器获取数据
【发布时间】: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 succeedCORS header 'Access-Control-Allow-Origin' missing。当我使用 Postman 时,一切都很好,我得到了带有我想要的数据的 json 对象。

【问题讨论】:

标签: php reactjs rest api


【解决方案1】:

尝试添加:

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

.htaccess文件

【讨论】:

  • 我已将 proxy 添加到 package.json 但现在我收到此错误:error SyntaxError: "JSON.parse: unexpected character at line 1 column 1 of the JSON data"
  • 尝试记录纯文本响应
  • 我使用 response.text() 代替 .json() ii 得到 my-site.com/api HTML,它是 404,但在浏览器中 my-site.com/api 我得到 json跨度>
【解决方案2】:

问题解决了。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-09
    • 2022-12-04
    • 2021-07-30
    • 1970-01-01
    • 2013-07-27
    • 1970-01-01
    • 2019-10-19
    • 2016-08-03
    相关资源
    最近更新 更多