Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Axios posts as JSON object, how to change

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.

like image 479
A. L Avatar asked Jan 05 '17 23:01

A. L


People also ask

Does Axios convert JSON to object?

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.

Does Axios post send JSON?

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.

How pass JSON data in Axios POST 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);

Does Axios automatically convert to JSON?

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.


1 Answers

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);
like image 152
Armino Popp Avatar answered Sep 29 '22 12:09

Armino Popp