Home  >  Article  >  Backend Development  >  Why Doesn\'t Axios POST Populate $_POST in PHP with JSON Data?

Why Doesn\'t Axios POST Populate $_POST in PHP with JSON Data?

Linda Hamilton
Linda HamiltonOriginal
2024-10-23 01:04:30441browse

Why Doesn't Axios POST Populate $_POST in PHP with JSON Data?

Axios POST Parameters Not Populating $_POST

When using Axios to perform a POST request with a payload consisting of JSON data, PHP may not interpret the parameters correctly from $_POST or $_REQUEST. Instead, the request data is often accessible through file_get_contents("php://input").

Root Cause:

By default, Axios serializes JavaScript objects to JSON. PHP, however, does not support JSON as a native data format for $_POST population. It only accepts the machine-processable formats supported by HTML forms:

  • application/x-www-form-urlencoded
  • multipart/form-data

Solution:

To resolve this issue, you can modify the Axios request to send data in the application/x-www-form-urlencoded format, which PHP can correctly handle. There are two primary options:

1. Using URLSearchParams API (Browser-Only):

var params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/foo', params);

2. Using qs Library (Node.js):

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

These methods ensure that the request data is properly serialized to application/x-www-form-urlencoded format, making it accessible through $_POST in PHP.

Alternatively, you could modify PHP to handle JSON as a valid data format for $_POST, but this approach is less recommended.

The above is the detailed content of Why Doesn\'t Axios POST Populate $_POST in PHP with JSON Data?. 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