Table of Contents
On the web, headers are used to pass information about the request and response.
Therefore, it can be very useful to know how to add your own headers to requests that you make using the popular Axios HTTP library.
In this post, we'll learn how to add headers to your Axios requests.
How to add headers to your Axios requests
Let's start with a basic GET request:
JAVASCRIPTconst response = await axios.get("https://sabe.io/");
console.log(response.data);
Now, let's add an authorization header to our request by utilizing the options object as our second parameter.
JAVASCRIPTconst options = {
headers: {
Authorization: "Bearer <your-token>"
}
};
const response = await axios.get("https://sabe.io/", options);
console.log(response.data);
Now this request should have an authorization header on it.
Let's look at how we can pass headers using POST instead of GET:
JAVASCRIPTconst payload = {
email: " <your-email>",
password: "<your-password>"
};
const options = {
headers: {
Authorization: "Bearer <your-token>"
}
};
const response = await axios.post("https://sabe.io/", payload, options);
console.log(response.data);
In this case, we have to pass the options as the third parameter because the second one is being used for the payload.
Keep in mind that this will also work with PUT and DELETE.
Conclusion
In this post, we learned how to add headers to your Axios requests.
Simply create an options object, add your headers, then pass in the options object to Axios.
Thanks for reading!
- How to Install Node on Windows, macOS and Linux
- Managing PHP Dependencies with Composer
- Getting Started with Express
- Best Visual Studio Code Extensions for 2022
- How to deploy a MySQL Server using Docker
- How to deploy an Express app using Docker
- Getting Started with Sass
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting Started with Moment.js
- Using Push.js to Display Web Browser Notifications
- Building a Real-Time Note-Taking App with Vue and Firebase
- Setting Up Stylus CSS Preprocessor