POST Requests with Axios

Sep 17, 2019

The easiest way to make a POST request with Axios is the function. The first parameter to is the URL, and the 2nd is the HTTP request body.

const res = await'', { hello: 'world' });; // { hello: 'world' }

By default, if the 2nd parameter to is an object, Axios serializes the object to JSON using the JSON.stringify() function. If the 2nd parameter is an object, Axios also sets the content-type header to application/json, so most web frameworks, like Express, will be able to automatically convert the request body into a JavaScript object for you.

const res = await'', { hello: 'world' });['Content-Type']; // application/json;charset=utf-8

To override the content-type header in Axios, you should use the third parameter to the options parameter. Set the options.header['content-type'] option to set the content-type header.

const res = await'', { hello: 'world' }, {
  headers: {
    // 'application/json' is the modern content-type for JSON, but some
    // older servers may use 'text/json'.
    // See:
    'content-type': 'text/json'
});['Content-Type']; // text/json

Form-Encoded Request Bodies

If you pass a string as the body parameter to, Axios will set the content-type header to application/x-www-form-urlencoded. That means that the string passed in as the request body should contain a bunch of key/value pairs separated by &, in the format of key1=value1&key2=value2.

const res = await'', 'hello=world');; // { hello: 'world' }['Content-Type']; // application/x-www-form-urlencoded

You can also POST using JavaScript's FormData class to POST more sophisticated data, including files.

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!