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?

4
  • 1
    I highly recommend you to add to the post the tag of the backend language. It is PHP? Commented Jul 9, 2020 at 18:56
  • Maybe it is because of CORS. Can you open the browser console and check for errors at client side too? Commented Jul 9, 2020 at 19:03
  • Possible duplicate of stackoverflow.com/questions/35192841/… Commented Jul 9, 2020 at 19:05
  • @Aykhan: Nope, no issues there. Commented Jul 9, 2020 at 19:18

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

You were almost right, but it should be "input" instead of "stdin". Now working like a charm.
@Armin Hierstter : indeed, I mixed up, thanks for the edit

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.