0

I'm trying to make an application that sends JSON data to PHP server, and get responses from it. I'm using JavaScript node-fetch library for it.

Here is my sample code:

    const fetch = require("node-fetch");
    let data = JSON.stringify(something);

    fetch("https://example.com/api", {
        method: "post",
        body: data,
        headers: { 'Content-Type': 'application/json' }
    })
        .then(res => res.text())
        .then(ret=>{
            console.log(ret);
        });

I'm trying to get this with $_POST in PHP:

var_dump($_POST);

But it returns empty array.

How can I get this on PHP, or do I do something wrong?

sundowatch
  • 3,012
  • 3
  • 38
  • 66

1 Answers1

3

$_POST is only filled with values when receiving a request body with the application/x-www-form-urlencoded or multipart/form-data Content-Type header.

So you need to handle the JSON body like this:

$inputJSON = file_get_contents("php://input");
$input = json_decode($inputJSON, true);

var_dump($input);
Marco
  • 7,007
  • 2
  • 19
  • 49