I’m having trouble posting data to an API using Fetch. I’ve simplified it to the following:
I created a simple PHP file at https://sophivorus.com/post.php with the following code:
<?php
echo json_encode( $_POST );
If I browse to it, open the dev console, and run the following simple command:
fetch( 'https://sophivorus.com/post.php', {
method: 'POST',
} ).then( response => response.json() ).then( console.log );
I get a valid, empty JSON response. However, if I add a payload:
fetch( 'https://sophivorus.com/post.php', {
method: 'POST',
body: JSON.stringify( {
foo: 'bar'
} ),
} ).then( response => response.json() ).then( console.log );
I would expect to get a JSON response with the posted values. But I get the same, empty response. It seems that for some reason, my POST data is not getting posted.
I’m sure it must be something really stupid, but I just can’t see it. Any help would be most welcome, thanks!!