Axios is a popular JavaScript library that serves as a powerful HTTP client for making asynchronous HTTP requests in the browser and Node.js. It provides an easy-to-use interface and supports various features such as promise-based requests, interceptors for request and response handling, and the ability to cancel requests. Axios simplifies the process of sending HTTP requests and handling responses, making it a preferred choice for many developers for tasks like fetching data from APIs, interacting with servers, and managing HTTP requests and responses in web applications. Its flexibility and comprehensive functionality make it a valuable tool for building robust and efficient applications that rely on network requests.
HTTP Interceptors :
HTTP interceptors allow us to check or modify all the incoming or outgoing HTTP requests in our application. We can use them if we want to apply something like an authorization header to all the requests. Let's see how we can implement it using Axios.
Getting started with Axios
To install Axios in your project, you can use either npm (Node Package Manager) or Yarn (a package manager developed by Facebook). Both npm and Yarn allow you to manage and install JavaScript packages, including Axios. Here's how you can install Axios using npm or Yarn:
Axios Request Interceptor :
Let's see how we can use Axios to setup request interceptor that will run before a request is made.
import axios from 'axios';
/* The code `axios.interceptors.request.use((config) => { ... })` is creating an interceptor for Axios
requests. */
axios.interceptors.request.use((config) => {
// Log to print that request is intiated..
console.log('Request was sent');
// Data that can be keep track of which are sent in request
console.log(`[${config.method}] ${config.url}`);
console.log(`Headers :`);
console.log(config.headers);
console.log(`Params : `);
console.log(config.params);
console.log(`Data : `);
console.log(config.data);
return config;
});
const fetchQuotes = async () => {
try {
const res = await axios.get(`https://type.fit/api/quotes`);
} catch (error) {
console.log(error);
}
};
Setting Request Headers :
We can use request interceptors to set default HTTP headers that we want to send in every request.
Using request interceptors in Axios allows you to intercept outgoing requests before they are sent to the server. This feature is particularly useful for setting default configurations, headers, or any other properties that you want to apply to every request in your application. Here’s how you can use request interceptors to set default HTTP headers:
Response Interceptor :
Similarly, we can also setup a response interceptor with Axios that will execute whenever we receive API response.
Setting up a response interceptor with Axios allows you to intercept responses before they are handled by the then() or catch() methods. This feature is useful for globally handling errors, modifying the response data, or performing any other operations you require. Here's how you can set up a response interceptor with Axios:
// Axios response interceptor setup
axios.interceptors.response.use(
(response) => {
// Handle successful responses
console.log('Response received:', response.data);
return response;
},
(error) => {
// Handle response errors
console.error('Error encountered:', error);
return Promise.reject(error);
}
);
// Make a sample GET request
axios.get('https://jsonplaceholder.typicode.com/posts/1')
.then((response) => {
console.log('Response data:', response.data);
})
.catch((error) => {
console.error('Error fetching data:', error);
});
Also, please feel free to share your own tips in the comments. 🧐
👇 You can find and connect with me over 👇
Facebook
LinkedIn
Twitter
Github
Happy Coding and keep exploring!
Top comments (0)