0

In react i write

useEffect(() => {
    fetch("https://ozencalc.ru", {
      method: "POST",
      headers: {
        'Accept': 'application/json',
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        action: "operations-update"
      })
    })
      .then((res) => {
        return res.json();
      })
      .then((res) => alert(res));
  }, []);

so i'm sending an object as a body and expect to read it on php server where i write

echo json_encode($_POST);

but i get an empty array instead of object with key "action"

What can be the cause that php server variable $_POST doesn't content value

[
  "action" => "operations-update"
]

can it be some hosting server problem or i misunderstood how php works?

Dmitry Reutov
  • 2,995
  • 1
  • 5
  • 20
  • Is this really what your PHP code looks like? Because Postman request also returns `null`. so most likely not JS related – Justinas Apr 08 '22 at 19:47
  • Does this answers your question? https://stackoverflow.com/questions/39471257/post-is-empty-in-php5-6 – Justinas Apr 08 '22 at 19:49
  • 3
    Content-Type = `application/json` wont be in `$_POST`, `$_POST` gets filled when its `application/x-www-form-urlencoded` or `multipart/form-data` [is in the docs](https://www.php.net/manual/en/reserved.variables.post.php) you should use [file_get_contents('php://input')](https://www.php.net/manual/en/wrappers.php.php) – Lawrence Cherone Apr 08 '22 at 19:51

1 Answers1

3

Your $_POST will be empty because data was sent in body, try:

$data = json_decode(file_get_contents('php://input'), true);
Gabski
  • 46
  • 4
  • That ineed worked for me @Gabski. Question remains why not php reads an interprets the body? Certainly when `Content-Type` is set? – theking2 Apr 20 '22 at 15:23