Home > Backend Development > PHP Tutorial > 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
Release: 2024-10-22 23:17:29
Original
996 people have browsed it

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,
    }   
})  
Copy after login

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); 
      Copy after login
    • Use the qs library:

      var qs = require('qs');
      axios.post('/foo', qs.stringify({ 'bar': 123 }));
      Copy after login
  • 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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template