1

I'm trying to send API response from my Javascript file like this:

try {
  await fetch('https://example.com/api', {
      method: 'post',
      mode: 'no-cors',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        username: 'john',
      })
    }).then((response) => response.json())
    .then((data) => console.log(data));
} catch (e) {
  console.error(e);
}

Now I'm trying to get the body of the request.
My Backend Server built on PHP.
I have already seen this Stackoverflow Question.
As I saw there, I need to do this:

To access the entity body of a POST or PUT request (or any other HTTP method): $entityBody = file_get_contents('php://input');

This is my Index.php file:

<?php

$entityBody = file_get_contents('php://input');

echo json_encode($entityBody);

And it returns nothing. enter image description here

I'm new to PHP so maybe its a stupid mistake.

My goal is to print john in the console.

Barmar
  • 741,623
  • 53
  • 500
  • 612
Xacoio
  • 21
  • 5
  • `$entity_body` is already a JSON string, you don't need to call `json_encode()`. You would call `json_decode()` to convert it to a PHP array or object. – Barmar Oct 05 '22 at 15:41
  • What do you see as the raw response in the Network tab of the browser? – Barmar Oct 05 '22 at 15:44
  • If I try to decode it it shows me this error: `JSON Parse error: Unexpected EOF`. – Xacoio Oct 05 '22 at 15:58
  • I'm using React Native so I cant see the Network tab like browsers. – Xacoio Oct 05 '22 at 15:59
  • Check what your PHP script actually received. If you have no way of inspecting the request client-side, then write the contents of `php://input` to a file on the server, and then check what that contains after. – CBroe Oct 06 '22 at 08:05
  • It shows nothing in the file. I have created a basic HTML with this script to check it on client-side, and it shows nothing, there is no response. – Xacoio Oct 06 '22 at 09:38

0 Answers0