Skip to content
Advertisement

React can’t get response body from PHP API

I’m trying to send a POST request to my PHP file and get a response. The response is sent with code 200, however, I don’t see what PHP returns. Here is my react code:

useEffect(()=>{
    const requestOptions = {
        method: 'POST',
        headers: {'Content-Type': 'application/json' },
        body: JSON.stringify({ title: 'Hello!' })
    }

    fetch('http://localhost:80/react/db.php',requestOptions)
    .then((response) => {
      console.log(response)
    })
    .catch(err => {
      alert('error')
    })
  },[])

And here is my PHP code:

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
header("Content-type:application/json");
echo "data";

Logging response on console returns me: enter image description here
I can’t get the “data” out of PHP.

Advertisement

Answer

 fetch('http://localhost:80/react/db.php',requestOptions)
.then((response) => response.json())
.then(data => {
    console.log(data)
}).catch(err => {
  alert('error')
})
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement