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:
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!