Axios posting params not read by $_POST

From the documentation (I haven’t preserved links in the quoted material):

Using application/x-www-form-urlencoded format

By default, axios serializes JavaScript objects to JSON.

PHP doesn’t support JSON as a data format for populating $_POST.

It only supports the machine-processable formats natively supported by HTML forms:

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

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:

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

Note that URLSearchParams is not supported by all browsers, but there
is a polyfill available (make sure to polyfill the global
environment).

Alternatively, you can encode data using the qs library:

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

Or you could customise your PHP so it can handle JSON as per this answer on another question.

Leave a Comment