23

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.

A. L
  • 11,695
  • 23
  • 85
  • 163
  • axios uses JSON as default content type. In [this URL](https://github.com/mzabriskie/axios/issues/97) you can find several workarounds and solutions for this problem. – Fma Jan 11 '17 at 08:34
  • I will try it out tomorrow and let you know the results – A. L Jan 11 '17 at 09:18
  • Well as long as it helps :) – Fma Jul 09 '18 at 09:15
  • -1 because HTTP headers are NOT case sensitive; see https://stackoverflow.com/questions/5258977/are-http-headers-case-sensitive – KBoek Nov 08 '18 at 12:55
  • @KBoek Yes by RFC definition they are not but at the time of my answer there was a problem with lowercase headers using this library. I just checked it and now it works as per RFC so updating my answer. Thanks for letting me know! – Fma Nov 09 '18 at 13:21
  • @Fma, OK, I reversed the -1 :) – KBoek Nov 10 '18 at 09:45
  • did you resolved it ? – Rebai Ahmed Jul 16 '19 at 12:28

1 Answers1

13

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);
Armino Popp
  • 348
  • 5
  • 11
  • Using a mix of `urlsearchparams` and the `data` property must also work: `var params=new URLSearch...;options=...data: params`. But it does not work, in the error the data property is empty. I want to use GoogleTrans of [Rapidapi](https://rapidapi.com/googlecloud/api/google-translate1/) – Timo Oct 16 '22 at 17:01
  • Although in the RapdiApi Example it is done with `urlsearchparams` it did not work. But with `qs` in ES6 it works. – Timo Oct 16 '22 at 17:16