Home  >  Article  >  Backend Development  >  Why is Axios POST Request Data Missing from PHP\'s $POST and $REQUEST Variables?

Why is Axios POST Request Data Missing from PHP\'s $POST and $REQUEST Variables?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-22 23:17:29897browse

Why is Axios POST Request Data Missing from PHP's $POST and $REQUEST Variables?

Axios Posting Parameters Unavailable in PHP Variables

This code snippet uses the Axios library to make a POST request, setting the Content-Type header to application/x-www-form-urlencoded:

axios({
    method: 'post',
    url,
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    data: {
        json,
        type,
    }   
})  

However, the equivalent PHP variables, $_POST and $_REQUEST, remain empty after the request. Instead, file_get_contents("php://input") appears to be receiving the data.

Cause and Solution

The discrepancy arises from how Axios serializes data by default. It converts JavaScript objects to JSON, which PHP does not natively support for populating $_POST. PHP only accepts the machine-processable formats supported by HTML forms: application/x-www-form-urlencoded and multipart/form-data.

To address this, you have several options:

  • Browser:

    • Use the URLSearchParams API:

      var params = new URLSearchParams();
      params.append('param1', 'value1');
      params.append('param2', 'value2');
      axios.post('/foo', params); 
    • Use the qs library:

      var qs = require('qs');
      axios.post('/foo', qs.stringify({ 'bar': 123 }));
  • Customizing PHP:

    • Adjust PHP to handle JSON as per this answer: [link to answer]

The above is the detailed content of Why is Axios POST Request Data Missing from PHP\'s $POST and $REQUEST Variables?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn