POST Requests with Axios

Sep 17, 2019

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

const res = await axios.post('https://httpbin.org/post', { hello: 'world' });

res.data.json; // { hello: 'world' }

By default, if the 2nd parameter to axios.post() 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 axios.post('https://httpbin.org/post', { hello: 'world' });

res.data.headers['Content-Type']; // application/json;charset=utf-8

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

const res = await axios.post('https://httpbin.org/post', { hello: 'world' }, {
  headers: {
    // 'application/json' is the modern content-type for JSON, but some
    // older servers may use 'text/json'.
    // See: http://bit.ly/text-json
    'content-type': 'text/json'
  }
});

res.data.headers['Content-Type']; // text/json

Form-Encoded Request Bodies

If you pass a string as the body parameter to axios.post(), 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 axios.post('https://httpbin.org/post', 'hello=world');

res.data.form; // { hello: 'world' }
res.data.headers['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!