0

I want to learn how fetch works. Backend is very simple

<?php
    print_r(json_encode($_POST['test']));

And I created this fetch

fetch('http://localhost/test.php', {
    method: 'POST',
    body: JSON.stringify({
        test: 'test'
    })
})
     .then(res => res.json())
     .then(data => console.log(data))

All the time this code return null in console.log. Where I make a mistake?

KaKi786
  • 53
  • 1
  • 2
  • 6

1 Answers1

0

You have two problems.

Strings and Fetch

If you POST a string using fetch it will default to sending it with a Content-Type: text/plain header.

Plain text isn't JSON. Specify the correct Content-Type.

fetch('http://localhost/test.php', {
    method: 'POST',
    headers: {
        "Content-Type": "application/json",
    },
    body: JSON.stringify({
        test: 'test'
    })
})

PHP won't process JSON formatted requests automatically

You need to read the raw body and parse it yourself. This is a FAQ. Here is the solution.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • I don't need to use JSON. I can use only `$_POST['test']` but I found this method. Can I remove JSON.stringify? – KaKi786 Sep 02 '21 at 17:05
  • Not unless you replace it with something to convert the object to the data format you want to use instead – Quentin Sep 02 '21 at 17:07
  • OK. I do that and I see In chrome (tab network), that response is correctly but in the console I have this error `Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data` – KaKi786 Sep 02 '21 at 17:40
  • `print_r` doesn't output JSON – Quentin Sep 02 '21 at 17:43
  • No. I commented print_r (I have only `$data = json_decode(file_get_contents('php://input'), true);` in my php file) and I have this same error. Could you show my correctly code? – KaKi786 Sep 02 '21 at 18:25
  • So now you're outputting **nothing**. Trying to parse nothing as JSON will throw an error because "nothing" isn't JSON. – Quentin Sep 02 '21 at 18:33
  • OK. But if I good understand this code decode all POST request from json? So how can I return that console.log could print that? – KaKi786 Sep 02 '21 at 18:39
  • `print` some JSON. – Quentin Sep 02 '21 at 18:39