A Complete Guide to Axios POST Requests

Hamza Sabljakovic
JavaScript in Plain English
3 min readNov 23, 2021

--

Photo by Oskar Yildiz on Unsplash

Introduction

With over 21 million downloads from NPM per week, axios is one of the most beloved HTTP clients in the JavaScript ecosystem. The concise and intuitive library’s API together with a rich set of third-party plugins/extensions makes this HTTP client choice of many web and Node.js developers.

Before we dive into examples, I just want to point out that there are different ways (styles) of writing HTTP requests with axios, for example, creating a new instance and invoking methods on the created instance. However, in this post, we will use a global instance in combination with request methods aliases.

Request body

axios.post('URL', { name: 'Bob' }).then(console.log)

In the case of an HTTP POST (or PUT and PATCH), the request body is the second parameter the method takes. By default, without any configuration, the axios assumes the intention is to send a JSON body and treats it as such. In other words, JavaScript objects are serialized to a JSON before being sent to a server.

Form url encoded — x-www-form-urlencoded

However, in some cases, there is a need to send a POST request which body is not JSON but Form data.

When it comes to sending a form POST request, there is an additional step required. Depending on if you are using axios in Node.js or browser the configuration is a bit different.

In Node.js, we can use a built-in library querystring.

axios.post('URL', querystring.stringify({ 'name': 'Bob' }))
.then(console.log)
.catch(console.error)

On the other hand, in browsers, we can relay on the browser’s native URLSearchParams.

const params = new URLSearchParams();
params.append('name', 'Bob');
axios.post('URL', params);

Request Headers

Besides sending a request body to a server, we usually need to include additional information about our request, a very common example of such a requirement is auth token or key. In axios, attaching a header to a request is very straightforward, it’s done by passing a third parameter to the axios.post method.

axios.post('', {}, { headers: { 'api-key': 'x'}}).then(console.log)

However, under the hood, the library appends additional headers about the request. It’s worth mentioning that without those headers, such as content-type and content-length, some of the servers have trouble parsing the body contents, or requests would be considered invalid and rejected. The process of appending headers is not unique to axios, the majority of HTTP clients do the same process.

A complete list of default headers when sending a JSON body request.

All headers present in the case of form data

Additional configuration

Few other useful configuration options that are not specific for POST requests but are still worth mentioning.

  1. Adding a request timeout is done the same way headers are passed as the 3rd method parameter, the timeout in milliseconds can be defined.
axios.post('...', {name: 'Bob'}, {timeout: 30000}) //30 sec timeout

2. keep-alive option (Node.js-only feature), to signal the server to keep to underlying TCP connection open, which in turn makes subsequent requests faster (as the process of establishing a new TCP connection is completely skipped)

httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }),

3. Axios has built-in support for basic auth-protected APIs. Again, it’s done in the same way headers are (3rd method parameter). You can read more about it here.

auth: {
username: 'janedoe',
password: 's00pers3cret'
},

4. Set a global base URL — axios.defaults.baseURL = 'https://localhost:3000/api/';

I hope you found this useful and if you are interested in learning more about the axios here are a few of my other posts.

More content at plainenglish.io. Sign up for our free weekly newsletter here.

--

--