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?
$_POST
is only filled with values when receiving a request body with theapplication/x-www-form-urlencoded
ormultipart/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);