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!!
3
Answers
Try to add
'Content-Type': 'application/json'
in your fetch header options. It helps the server to interpret the data you are sending.Ref: Is Content-Type mandatory in HTTP post request?
The problem is not related to fetch. A simple client request shows the same problem:
Response: []
The $_POST array is for request body urlencoded parameters, not json.
Try:
Using
FormData
instead ofJSON.stringify
works. I am not very well versed with PHP, but my theory is that PHP doesn’t parse JSON data automatically (when usingJSON.stringify
). You need to usejson_decode
first, before echoing thejson_encode
.FormData
on the other hand, is automatically parsed into$_POST
array.