0

I have the following js snippet:

    fetch('/some/webhook', {
        method: 'post',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({test:'1'})
    }).then(function(res) {
        // do something here
    }).then(function(data) {
        // do something else here
    });

For hours I am trying to get the body to my server, but the listening script sees nothing in the $_POST variable. The webhook receives the request. A simple:

die (var_dump($_POST));

results in an empty array shown in the console where I would have expected to see the variable test with value 1.

What is wrong?

Armin Hierstetter
  • 1,078
  • 2
  • 12
  • 27

1 Answers1

1

The way you are sending your data, php will not populate de _POST variable

If you want to send json content, you should do

$data = json_decode(file_get_contents('php://input'), true);

echo $data["test"];

Alternative solution, if you'd rather have your data in _POST you should send a multipart/form-data header and use a new FormData(); as the body of fetch.

smwhr
  • 675
  • 6
  • 22