0

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

<?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

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. When im using Postman, everything it's ok, and I get json object with data I wanted.

2

2 Answers 2

0

Try to add :

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

To .htaccess file

Sign up to request clarification or add additional context in comments.

4 Comments

I have add proxy to package.json but now i get this error: error SyntaxError: "JSON.parse: unexpected character at line 1 column 1 of the JSON data"
Try log the plain text response
I use response.text() instead .json() i i get my-site.com/api HTML and it's 404, but in browser in my-site.com/api i get json
0

Problem solved.

I tryed to fetch data from my-site.com/api but I should fetch from my-site.com/api/index.php

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.