As far as MDN says, the right way to do a POST request with fetch and sending data is: (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch)
var url = 'https://example.com/profile';
var data = {username: 'example'};
fetch(url, {
method: 'POST', // or 'PUT'
body: JSON.stringify(data), // data can be `string` or {object}!
headers:{
'Content-Type': 'application/json'
}
}).then(res => res.json())
.then(response => console.log('Success:', JSON.stringify(response)))
.catch(error => console.error('Error:', error));
but I spent 2 days trying to make it work (Chrome, Firefox, Edge) but I couldn't... the problem is that body isn't sent to server (GET request works ok), is not server problem, (I'm using PHP 7 on same machine), I debugged the request and no body content at all was sent to server...
At last, and with the help of two friends, we realized than using other header and other body format, body was sent. These are my test files that work:
<body>
<button onclick='buttonOneClick()'>One (GET)</button>
<button onclick='buttonTwoClick()'>Two (POST)</button>
<script>
function buttonOneClick(){
fetch('server.php?text=one&id=1')
.then(r => r.text())
.then(res => alert('you sent '+res));
}
function buttonTwoClick(){
let data = "text=two&id=1";
fetch('server.php', {
method: 'POST',
body: data,
headers: {
'Content-Type':'application/x-www-form-urlencoded',
},
})
.then(r => r.text())
.then(res => alert('you sent '+res));
}
</script>
</body>
and server file, in PHP:
<?php
$param = $_REQUEST['text'] ?? "nothing";
print $param;
I had to use an "application/x-www-form-urlencoded" instead of "application/json" Content type header and using a string for "body" property.
This is the ONLY way "body" is sent in a fetch POST request... And yes, when I was using "application/json" header and JSON.stringify for body, I tried using a lot of properties, such as "mode", "cache", "credentials"... and "POST" and/or "Content-Type" in lowercase... and simple and double quotes in json data... but nothing worked