Home > database >  Don't get text back from HTTP fetch request with status 200
Don't get text back from HTTP fetch request with status 200

Time:08-11

I'm new to react and try to send a request to my local apache server (run via xampp).

fetch('http://localhost:80', {
    method: 'POST',
    headers: {'Accept': 'text/*'}    
}).then(
    (response) => {response.text();}
).then(
    (msg) => {console.log(msg)}
).then(
    (error) => {console.log(error)}
);

The response returns the status code 200. The php script writes to a text file and echos Hello World.

<?php
header('Access-Control-Allow-Origin: http://localhost:3000');
$FILE = fopen("test.txt", "w");
fwrite($FILE, "Hello World");
?>
Hello World!

After executing the fetch, the console contains [undefined] twice. I previously logged the response, which contains an empty text attribute (and an empty json attribute), as well as status code 200 (Success). Also, the text-file is created, so the php-script definitely runs.

How can I see Hello World?

CodePudding user response:

you have to return response from the response.text() section..

}).then(
    (response) => { return response.text();}
).
 

or simply


}).then(
    (response) =>   response.text();
).

and also in error section use .catch instead of .then

  • Related