简体   繁体   中英

$_POST not retrieving data from Javascript's Fetch()

I'm posting data using javascript's fetch() .

    fetch('/string.php', {
      method: 'post',
      body: JSON.stringify({
        name: 'helloe world',
      })
    })
    .then(function(response) {
      if (response.status >= 200 && response.status < 300) {
        return response.text()
      }
      throw new Error(response.statusText)
    })
    .then(function(response) {
      console.log(response);
    })

string.php file contains:

print_r($_POST);

Now my problem is the $_POST returns an empty array. I can fix this by appending the file with:

$_POST = json_decode(file_get_contents('php://input'), true);

But that feels very hackish and isn't ideal. Is this the intended behaviour for PHP when retrieving post data from a JS fetch() ?

Is there anyway I may automatically put the contents within the $_POST ?

$_POST is only populated by application/x-www-form-urlencoded or multipart/form-data requests.

For any other data format, you will need to parse php://input manually. In your case, you're using json_decode and putting the result in the $_POST superglobal, which is an acceptable way to "convert" from JSON to form data.

But that feels very hackish and isn't ideal.

Assigning to $_POST is a bit weird. It is generally treated as read only. Most people would use another variable.

You should set the Content-Type on the request though, fetch will default to claiming a string is plain text unless you tell it otherwise.

Is this the intended behaviour for PHP when retrieving post data from a JS fetch()?

No. It is the intended behaviour when PHP doesn't support the content-type of the request body.

Is there anyway I may automatically put the contents within the $_POST?

Send form encoded or multipart data instead of JSON encoded data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM