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:
JavaScript
x
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:
JavaScript
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:
I can’t get the “data” out of PHP.
Advertisement
Answer
JavaScript
fetch('http://localhost:80/react/db.php',requestOptions)
.then((response) => response.json())
.then(data => {
console.log(data)
}).catch(err => {
alert('error')
})