0

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?

infinitezero
  • 1,610
  • 3
  • 14
  • 29

1 Answers1

3

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

sms
  • 1,380
  • 1
  • 3
  • 5
  • Ah, so my mistake was I combined both solutions, which creates a void function? – infinitezero Aug 11 '22 at 15:01
  • 1
    yes .. i believe this would help u... https://stackoverflow.com/questions/28889450/when-should-i-use-a-return-statement-in-es6-arrow-functions – sms Aug 11 '22 at 15:04