As the title states, when you do a
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
The data will be in a JSON object, and thus will not be detected by $_REQUEST
, and can only be found in php://input
.
Is there anyway to change this? I've tried changing the content-type
as well, but that didn't help.
When making a POST or PUT request, Axios will automatically parse the data to JSON, provided you are sending an object, and make the necessary adjustments elsewhere in the request so it can be automatically parsed once received by the server.
How to Send POST JSON Requests Using Axios. The POST request is used to send data to an endpoint. For example, if we have a registration page where users submit their information, this information can be sent as JSON to the endpoint we specify using a POST JSON request.
To post request with JSON data with Axios, we call axios. post with the JSON payload as the 2nd argument. const dt = { data: { value: "abc" } }; const request = axios. post(url, dt);
Axios automatically converts the data to JSON, so you don't have to: // axios const url = 'https://jsonplaceholder.typicode.com/posts' const data = { a: 10, b: 20, }; axios . post(url, data, { headers: { Accept: "application/json", "Content-Type": "application/json;charset=UTF-8", }, }) . then(({data}) => { console.
Here is what is explained on the github axios page:
By default, axios serializes JavaScript objects to JSON. To send data in the application/x-www-form-urlencoded format instead, you can use one of the following options.
Browser
In a browser, you can use the URLSearchParams API as follows:
const params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/foo', params);
Note that URLSearchParams is not supported by all browsers (see caniuse.com), but there is a polyfill available (make sure to polyfill the global environment).
Alternatively, you can encode data using the qs library:
const qs = require('qs');
axios.post('/foo', qs.stringify({ 'bar': 123 }));
Or in another way (ES6),
import qs from 'qs';
const data = { 'bar': 123 };
const options = {
method: 'POST',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
data: qs.stringify(data),
url,
};
axios(options);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With