How to Send Headers With an Axios POST Request

Introduction

Axios is an HTTP client library that is used to send asynchronous HTTP requests such as POST, GET, and DELETE to REST endpoints (mainly APIs). Some of these requests, such as GET and POST, can include headers, which provide an additional source of information for each API call.

In this article, we will learn how to send headers alongside our POST request in Axios.

Headers are critical when making API requests and are one of the first places we look when we encounter problems with an API because they help us track down any potential issues.

POST Request Structure in Axios

An Axios POST request can accept three parameters: the endpoint's URL, data, and the configuration object, which accepts headers:

const res = await axios.post(URL, data, config);

Sending Headers with Axios POST Request

When passing headers into Axios, we supply an object containing the headers we want to pass as the config parameter. For example, assume we want to send a POST request to a server that accepts only text/json content type (instead of the usual application/json). In that case, we can customize the content type we want to send in the header:

const result = await axios.post('https://testapi.org/post', { name: 'John Doe' }, {
    headers: {
        'content-type': 'text/json'
    }
});

Alternatively, we can use variables instead of passing these objects directly into the axios.post() method. This definitely improves readability of our code:

const headers = {
    "Content-Type": "text/json"
};

const data = {
    name: "John Doe"
};

const result = await axios.post("https://testapi.org/post", data, {
    headers: headers
});

Let's just quickly confirm this works as expected:

console.log(result.data.headers['Content-Type']);
// Prints: text/json

Conclusion

In this article, we learned how to send headers with POST requests in Axios, as well as the structure of an Axios request, so that we do not mistake the config object for the data object, as many people do.

Last Updated: February 28th, 2023
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Joel OlawanleAuthor

Frontend Developer & Technical Writer

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms