Axios is a popular JavaScript library used for making HTTP requests. It provides a clean, promise-based API to interact with RESTful endpoints and other data sources. Whether you’re working with Node.js or in the browser, Axios simplifies data fetching, sending requests, and error handling.


Table of Contents

SectionTopic
1Introduction to Axios
2Installation
3Features of Axios
4Making HTTP Requests
4.1GET Requests
4.2POST Requests
4.3PUT Requests
4.4DELETE Requests
5Axios Configuration
5.1Global Configuration
5.2Instance Configuration
6Handling Responses
6.1Response Data
6.2Response Headers
7Error Handling
8Axios Interceptors
9Working with Headers
10Canceling Requests
11Using Axios with Async/Await
12Handling Timeouts
13Uploading and Downloading Files
14Axios and Authentication
14.1Token-Based Authentication
14.2Cookies and Session Management
15Advanced Axios Use Cases
15.1Retry Requests
15.2Request Queues
16Comparing Axios to Fetch API
17Conclusion

1. Introduction to Axios

Axios is a promise-based HTTP client for JavaScript. It is designed to work both in the browser and in Node.js, making it highly versatile for web and backend development. Axios helps developers handle asynchronous data fetching and provides utility features to simplify the process of working with APIs.

Key Features

  1. Promise-based API: Leverages modern JavaScript promises for easier asynchronous handling.
  2. Built-in JSON transformation: Automatically converts request and response data to JSON.
  3. Interceptors: Middleware-like functionality for transforming requests and responses.
  4. Global configuration: Easily set default headers, base URLs, and other settings.
  5. Browser support: Handles cross-browser issues seamlessly.
axios
axios

2. Installation

Axios can be installed via npm, yarn, or directly included via a CDN.

Using npm

Using yarn

Using a CDN

After installation, you can import Axios in your JavaScript files:


3. Features of Axios

3.1 Request Methods

Axios supports all standard HTTP methods: GET, POST, PUT, DELETE, PATCH, and OPTIONS.

3.2 Default Configuration

Set default headers, base URLs, and timeout settings for all requests.

3.3 Request and Response Interceptors

Intercept and transform requests or responses before they are sent or processed.

3.4 Error Handling

Provides detailed error objects with status codes, headers, and request data.

3.5 Supports Promises and Async/Await

Simplifies asynchronous operations with modern JavaScript syntax.


4. Making HTTP Requests

4.1 GET Requests

GET requests retrieve data from a server.

GET with Query Parameters

4.2 POST Requests

POST requests send data to a server.

4.3 PUT Requests

PUT requests update existing resources.

4.4 DELETE Requests

DELETE requests remove resources.


5. Axios Configuration

5.1 Global Configuration

5.2 Instance Configuration


6. Handling Responses

6.1 Response Data

Axios wraps server responses in an object containing the data, status, statusText, headers, and config.

6.2 Response Headers


7. Error Handling

Axios provides a detailed error object for failed requests.


8. Axios Interceptors

Axios interceptors are a powerful feature that allows you to modify requests and responses globally before they are sent to the server or received by the application. Interceptors act as middleware, providing a centralized way to handle common tasks like authentication, logging, or transforming data.

Why Use Axios Interceptors?

Interceptors streamline repetitive tasks in API interactions, offering benefits such as:

  1. Centralized Logic: Avoid duplicating logic across multiple requests or responses.
  2. Preprocessing Requests: Modify or enrich request data before it reaches the server.
  3. Postprocessing Responses: Transform or validate response data before using it.
  4. Error Handling: Manage API errors in a standardized way.

Request Interceptor

Response Interceptor

Example:

Managing Multiple Interceptors

Sometimes, you may need to add multiple interceptors for different purposes. Axios provides a use method to register them sequentially. Interceptors execute in the order they are added for requests and in reverse order for responses.

Removing Axios Interceptors

You can remove interceptors using the eject method, which takes the interceptor’s ID as an argument. The use method returns this ID when registering the interceptor.


9. Working with Headers

Custom headers can be set at the request or global level.


10. Canceling Requests


11. Using Axios with Async/Await

When working with Axios, the combination of async/await syntax can make asynchronous operations more intuitive and readable compared to chaining .then() and .catch(). This modern JavaScript feature simplifies handling promises, providing cleaner and more maintainable code, especially for complex API workflows.

Why Use Async/Await with Axios?

  1. Improved Readability: Code written with async/await is more sequential and resembles synchronous logic, making it easier to understand.
  2. Error Handling: Simplifies try-catch blocks for handling errors compared to .catch() in promise chains.
  3. Chaining Multiple Requests: Makes it easier to handle multiple dependent API calls sequentially or concurrently.
  4. Cleaner Code: Reduces nested code, which improves readability and maintainability.

Handling Multiple Requests with Async/Await

1. Sequential Requests

You can make multiple API calls sequentially using await.

2. Concurrent Requests

To make multiple requests concurrently, use Promise.all with await.

Best Practices for Using Async/Await with Axios

  1. Always Use Try-Catch: Prevent unhandled promise rejections by wrapping await calls in a try-catch block.
  2. Centralize Axios Configuration: Use a custom Axios instance with predefined settings to avoid redundant configurations.
  3. Leverage Async/Await for Clarity: Prefer async/await for complex workflows to make code more readable and maintainable.
  4. Handle Errors Gracefully: Implement detailed error-handling strategies based on HTTP status codes or other response attributes.
  5. Avoid Blocking Code: Use concurrent requests with Promise.all to improve performance when fetching independent data.

12. Handling Timeouts


13. Uploading and Downloading Files

Uploading Files

Downloading Files


14. Axios and Authentication

Token-Based Authentication

Bearer tokens are widely used in APIs for token-based authentication. You include the token in the Authorization header of your requests.

Cookies and Session Management

Some APIs use cookies to manage user sessions. Axios supports cookies by setting the withCredentials option to true.


15. Advanced Axios Use Cases

Retry Requests

Request Queues


16. Comparing Axios to Fetch API

FeatureAxiosFetch
Promise-basedYesYes
InterceptorsYesNo
JSON HandlingAutomaticManual
Node.js SupportYesNo
Error HandlingBuilt-inLimited

17. Conclusion

Axios is a powerful library that simplifies HTTP requests and error handling in JavaScript applications. Its rich feature set and ease of use make it a great choice for developers building web or Node.js applications.

Check our more blogs

Top Contents

1. NextJs – Server-Side Rendering

2. React router DOM

3. How to create NPM Package?

4. React Hooks


Latest Post