0

I have problem when fetching json data that comes from the output of PHP script. Here is the code from the script :

header("Content-Type: application/json; charset=UTF-8");

$stmt = $mysqli->prepare($sql);
$stmt->execute();
$result = $stmt->get_result();
$response = $result->fetch_all(MYSQLI_ASSOC);

echo json_encode($response);

/*$fp = fopen('datakomp.json', 'w');
fwrite($fp, json_encode($response));
fclose($fp);*/

As seen in the commented part of the code, I use the same script to store the data in a json file. When fetching the data from the generated json data file, without any modification, my app runs well.
But when fetching the same data directly from the json string input from the above php script, an error appears : "Unexpected end of input". Using chrome dev tools, I see the header shows the status code of 200 (Ok), and in the preview, it displays the expected data.
I have checked that there is no difference between the data in the json file and the json string input.

Here is the code for fetching the data in my React app :

fetch('http://localhost:100/myreactappversi2/myapp2/public/data/tes2.php', {
        method: 'GET',
        headers:{
            'Content-Type': ['application/json','charset=UTF-8'],
        },
        mode: "no-cors",
        cache: "no-cache",
        credentials: "include"
    })
    .then(response => response.json())
    .then(rowData => this.setState({rowData}))
    .catch(error =>  alert("Error : " + error))

I have been trying to fix the problem, including alternating the content-type header, response.text, json.parse, etc, but the result is basically the same, as if the input was empty.

I expect the same json string input from the php script like when fetching the same data from json file. But as if the input was empty.

EDIT :
In reply to the comment received, here is my explanation :
I have read the post given by the link. There is some differences between my case with the one described in the link. The request in the link is POST, whereas mine is GET. In addition, as I already explained, I made a comparison for my GET request : one is from a json file, the other is from a json string, but both contain exactly the same data resulted from the same php script.
Setting "Access-Control-Allow-Origin" doesn't solve my problem. If I change the "mode" and/or "credentials" to the defaults or other values, then the error will be "Failed to fetch".

EDIT 2 : Yeah.. this problem may arise due to my lack of knowledge in HTTP and CORS. After I read thoroughly the documentation in MDN about those topics, I began to understand them better. So I modified my code, both in client-side (js file) and server-side (php file) as follows :

  1. In client-side (js file) :

    mode: "cors",
    cache: "no-cache",
    credentials: "include" // value of "omit" works too            
    

    at headers section, I add :

    'Origin':'http://localhost:3000'
    
  2. In server-side (php file), I add :

    if($_SERVER['HTTP_ORIGIN'] == "http://localhost:3000") {
        header('Access-Control-Allow-Origin: http://localhost:3000');
        header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
        header('Access-Control-Allow-Headers: origin, Content-Type');
        header('Access-Control-Allow-Credentials: true');
        //header('Access-Control-Max-Age: 1728000');
    }
    

After doing so, my app ran as expected. Of course, my code still needs refinement. But, essentially, Problem SOLVED.
I am glad now. :) Anyway, I should thank to sideshowbarker for his link which led me to read thoroughly the documentation of HTTP and CORS, including how to deal with CORS preflight in MDN.

Lex Soft
  • 2,308
  • 2
  • 13
  • 13
  • In fact the cause of the “unexpected end of input” problem described in this question is exactly the same as the cause of the duplicate: You’re setting mode: "no-cors", which causes your browser to block your frontend JavaScript code from accessing the response. So you end up getting “unexpected end of input” because there is no input (response) exposed to your frontend JavaScript. It makes no difference whether the method is GET or POST — in both cases, specifying mode: "no-cors" causes the browser to block your code from accessing the response. – sideshowbarker Jan 24 '19 at 00:20
  • Whatever other problem you might instead run into when you *don’t* specify mode: "no-cors" is a different problem than the one you’ve actually described in the question. – sideshowbarker Jan 24 '19 at 00:22

0 Answers0