How to Send Headers With an Axios POST Request

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']); // 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: June 27th, 2022
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

Getting Started with AWS in Node.js

Build the foundation you'll need to provision, deploy, and run Node.js applications in the AWS cloud. Learn Lambda, EC2, S3, SQS, and more!

© 2013-2022 Stack Abuse. All rights reserved.

DisclosurePrivacyTerms