Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

post data can't be send to server #190

Closed
hon opened this issue Aug 10, 2015 · 1 comment
Closed

post data can't be send to server #190

hon opened this issue Aug 10, 2015 · 1 comment

Comments

@hon
Copy link

hon commented Aug 10, 2015

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: 'test@xx.com'
  })
}).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?

@madebyherzblut
Copy link

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);

@dgraham dgraham closed this as completed Aug 10, 2015
@github-actions github-actions bot locked as resolved and limited conversation to collaborators Oct 8, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants