fetch
fetch copied to clipboard
post data can't be send to server
I want to sent data to server via post method:
fetch('/api.php', {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: '[email protected]'
})
}).then(function(response){
return response.text();
}).then(function(info){
console.log(info);
});
and the the simple php code is:
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, Accept, Authorization, X-Request-With');
header('Access-Control-Allow-Credentials: true');
if (isset($_POST['email'])){
die('good');
}
die('bad');
?>
I got 'bad' in console panel. If the php code is:
die($_POST['email']);
the console result will be:
<br />
<b>Notice</b>: Undefined index: email in <b>E:\static\api.php</b> on line <b>7</b><br />
what's wrong with my code?
When you are sending a JSON payload you have to decode it on the server. My PHP knowledge is a bit rusty, but it should be something like this:
$payload = file_get_contents('php://input');
$data = json_decode($payload);
var_dump($data);