You are currently viewing Introduction to Axios: A Beginner’s Guide

Introduction to Axios: A Beginner’s Guide

When developing web applications, interacting with APIs to fetch or send data is a common task. Axios, a popular JavaScript library, simplifies this process by providing a promise-based HTTP client that works seamlessly with modern JavaScript frameworks like React, Vue, and Angular. Its ease of use and versatility make it a preferred choice for developers seeking to streamline API interactions.

In this comprehensive guide, we’ll explore the capabilities of Axios, from setting it up in your project to making various types of requests, handling responses and errors, and utilizing advanced features like interceptors and request cancellation. By the end of this article, you’ll have a solid understanding of how to leverage Axios to enhance your web development projects.

What is Axios?

Axios is an open-source, promise-based HTTP client for JavaScript that allows developers to make HTTP requests to external resources. It supports the full spectrum of HTTP requests, including GET, POST, PUT, DELETE, and more. Axios is designed to work in both browser environments and Node.js, making it a versatile tool for any JavaScript developer.

Key Features of Axios

Axios offers a range of features that enhance the process of making HTTP requests:

  • Promise-based: Simplifies asynchronous programming with promises.
  • Request and Response Interceptors: Allows customization of request and response handling.
  • Automatic JSON Data Transformation: Automatically transforms JSON data when sending or receiving.
  • Support for Older Browsers: Compatible with Internet Explorer 11 and other older browsers.
  • Built-in Error Handling: Provides robust error handling out of the box.
  • Cancellation of Requests: Enables the cancellation of in-progress requests.

Setting Up Axios in Your Project

Installing Axios via npm/yarn

To get started with Axios, you need to install it in your project. If you’re using npm or yarn, you can install Axios with a simple command.

Using npm:

npm install axios

Using yarn:

yarn add axios

Setting Up Axios via CDN

If you prefer to include Axios via a Content Delivery Network (CDN), you can add the following script tag to your HTML file:

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

This approach is useful for quick setups or for use in environments where a package manager is not available.

Basic Configuration

After installation, you can configure Axios in your project by importing it (when using npm/yarn) or by accessing it globally (when using CDN) and setting default parameters. Here’s a basic example of how to set up Axios:

Using npm/yarn:

import axios from 'axios';

// Set a default base URL for all requests
axios.defaults.baseURL = 'https://api.example.com';

// Set default headers
axios.defaults.headers.common['Authorization'] = 'Bearer token';
axios.defaults.headers.post['Content-Type'] = 'application/json';

Using CDN:

<script>

  // Set a default base URL for all requests
  axios.defaults.baseURL = 'https://api.example.com';

  // Set default headers
  axios.defaults.headers.common['Authorization'] = 'Bearer token';
  axios.defaults.headers.post['Content-Type'] = 'application/json';
  
</script>

This configuration ensures that all your requests use the specified base URL and headers, reducing the need to specify them for each request.

Making GET Requests

GET requests are used to retrieve data from a server. With Axios, making a GET request is straightforward and involves specifying the endpoint you want to fetch data from.

Here’s an example of how to make a GET request using Axios:

Using npm/yarn:

import axios from 'axios';

// Function to fetch data from an API
const fetchData = async () => {

  try {
    const response = await axios.get('/data');
    console.log(response.data);
  } catch (error) {
    console.error('Error fetching data:', error);
  }
  
};

// Call the function to fetch data
fetchData();

Using CDN:

<script>

  // Function to fetch data from an API
  const fetchData = async () => {
  
    try {
      const response = await axios.get('/data');
      console.log(response.data);
    } catch (error) {
      console.error('Error fetching data:', error);
    }
	
  };

  // Call the function to fetch data
  fetchData();
  
</script>

The axios.get method initiates a GET request to the specified URL. The await keyword ensures that the function waits for the request to complete before continuing. If the request is successful, the response data is logged to the console. If an error occurs, it is caught by the catch block and logged to the console.

Handling Responses and Errors

When you make a request with Axios, the response object contains several properties, including data, status, statusText, headers, and config. These properties provide detailed information about the response, allowing you to handle it appropriately.

Here’s an example of how to handle responses and errors in Axios:

Using npm/yarn:

import axios from 'axios';

// Function to fetch data and handle responses and errors
const fetchData = async () => {

  try {
  
    const response = await axios.get('/data');
    console.log('Data:', response.data);
    console.log('Status:', response.status);
	
  } catch (error) {
  
    if (error.response) {
	
      // Server responded with a status other than 2xx
      console.error('Error response data:', error.response.data);
      console.error('Error response status:', error.response.status);
	  
    } else if (error.request) {
	
      // No response received from server
      console.error('Error request:', error.request);
	  
    } else {
	
      // Other errors
      console.error('Error message:', error.message);
	  
    }
  }
};

// Call the function to fetch data
fetchData();

Using CDN:

<script>

  // Function to fetch data and handle responses and errors
  const fetchData = async () => {
  
    try {
	
      const response = await axios.get('/data');
      console.log('Data:', response.data);
      console.log('Status:', response.status);
	  
    } catch (error) {
	
      if (error.response) {
	  
        // Server responded with a status other than 2xx
        console.error('Error response data:', error.response.data);
        console.error('Error response status:', error.response.status);
		
      } else if (error.request) {
	  
        // No response received from server
        console.error('Error request:', error.request);
		
      } else {
	  
        // Other errors
        console.error('Error message:', error.message);
		
      }
    }
  };

  // Call the function to fetch data
  fetchData();
  
</script>

In this example, we extend the fetchData function to handle different types of errors. The axios.get method is used to make the request, and the response data and status are logged to the console if successful.

The catch block differentiates between three types of errors:

  • Error response: The server responded with a status code other than 2xx.
  • Error request: The request was made, but no response was received.
  • Other errors: Any other errors that might occur, such as network issues.

By handling these different error scenarios, you can ensure that your application responds appropriately to various error conditions.

Making POST Requests

POST requests are used to send data to a server, typically to create or update resources. Axios makes it easy to send POST requests with its axios.post method.

Here’s an example of how to make a POST request using Axios:

Using npm/yarn:

import axios from 'axios';

// Function to send data to an API
const postData = async () => {

  try {
  
    const response = await axios.post('/submit', {
      name: 'Edward Nyirenda Jr.',
      email: 'edward@coderscratchpad.com'
    });
	
    console.log('Response data:', response.data);
	
  } catch (error) {
    console.error('Error posting data:', error);
  }
  
};

// Call the function to send data
postData();

Using CDN:

<script>

	// Function to send data to an API
	const postData = async () => {


		try {

			const response = await axios.post('/submit', {
				name: 'Edward Nyirenda Jr.',
				email: 'edward@coderscratchpad.com'
			});

			console.log('Response data:', response.data);

		} catch (error) {
			console.error('Error posting data:', error);
		}

	};

	// Call the function to send data
	postData();

</script>

In this example, we define a function postData that sends a POST request to the /submit endpoint with a JSON payload containing name and email fields. The response data is logged to the console if the request is successful, and any errors are caught and logged.

The axios.post method is used to send the POST request. The first argument is the URL endpoint, and the second argument is the data payload to be sent. The await keyword ensures that the function waits for the request to complete before continuing.

Interceptors in Axios

Interceptors allow you to run your code or modify the request or response before they are handled by then or catch. This is useful for tasks like adding authorization tokens to requests or logging request and response details.

Here’s an example of how to use interceptors in Axios:

Using npm/yarn:

import axios from 'axios';

// Add a request interceptor
axios.interceptors.request.use(

  config => {
    console.log('Request made with ', config);
    config.headers.Authorization = 'Bearer token';
    return config;
  },
  
  error => {
    return Promise.reject(error);
  }
  
);

// Add a response interceptor
axios.interceptors.response.use(

  response => {
    console.log('Response received', response);
    return response;
  },
  
  error => {
    console.log('Error response', error.response);
    return Promise.reject(error);
  }
  
);

// Function to make a request
const fetchData = async () => {

  try {
  
    const response = await axios.get('/data');
    console.log('Data:', response.data);
	
  } catch (error) {
    console.error('Error fetching data:', error);
  }
  
};

// Call the function to fetch data
fetchData();

Using CDN:

<script>

  // Add a request interceptor
  axios.interceptors.request.use(
  
    config => {
      console.log('Request made with ', config);
      config.headers.Authorization = 'Bearer token';
      return config;
    },
	
    error => {
      return Promise.reject(error);
    }
	
  );

  // Add a response interceptor
  axios.interceptors.response.use(
  
    response => {
      console.log('Response received', response);
      return response;
    },
	
    error => {
      console.log('Error response', error.response);
      return Promise.reject(error);
    }
	
  );

  // Function to make a request
  const fetchData = async () => {
  
    try {
	
      const response = await axios.get('/data');
      console.log('Data:', response.data);
	  
    } catch (error) {
      console.error('Error fetching data:', error);
    }
	
  };

  // Call the function to fetch data
  fetchData();
  
</script>

In this example, we add request and response interceptors using axios.interceptors.request.use and axios.interceptors.response.use methods. The request interceptor logs the request configuration and adds an authorization header. The response interceptor logs the response details and handles errors.

By using interceptors, you can centralize and streamline request and response handling logic, making your code cleaner and more maintainable.

Cancelling Requests

Sometimes, you might need to cancel an ongoing request, for example, if the user navigates away from the page or if a new request supersedes the previous one. Axios provides a way to cancel requests using AbortController.

Here’s an example of how to cancel an Axios request using AbortController:

Using npm/yarn:

import axios from 'axios';

// Create an AbortController instance
let controller;

const fetchData = async () => {

	// Abort any previous request
	if (controller) {
		controller.abort();
	}

	// Create a new controller for the current request
	controller = new AbortController();
	const signal = controller.signal;

	try {

		const response = await axios.get('/data', { signal });
		console.log('Data:', response.data);

	} catch (error) {

		if (axios.isCancel(error)) {
			console.log('Request canceled', error.message);
		} else {
			console.error('Error fetching data:', error);
		}
	}
};

const cancelRequest = () => {

	if (controller) {
		controller.abort();
		console.log('Request canceled by the user.');
	}
};

// Call the function to fetch data
fetchData();

// Simulate a user action that cancels the request
setTimeout(() => {
	cancelRequest();
}, 1000);

Using CDN:

<script>

// Create an AbortController instance
let controller;

const fetchData = async () => {

	// Abort any previous request
	if (controller) {
		controller.abort();
	}

	// Create a new controller for the current request
	controller = new AbortController();
	const signal = controller.signal;

	try {

		const response = await axios.get('/data', { signal });
		console.log('Data:', response.data);

	} catch (error) {

		if (axios.isCancel(error)) {
			console.log('Request canceled', error.message);
		} else {
			console.error('Error fetching data:', error);
		}
	}
};

const cancelRequest = () => {

	if (controller) {
		controller.abort();
		console.log('Request canceled by the user.');
	}
};

// Call the function to fetch data
fetchData();

// Simulate a user action that cancels the request
setTimeout(() => {
	cancelRequest();
}, 1000);
  
</script>

In this example, we use AbortController to handle the cancellation. The fetchData function creates a new AbortController and uses its signal property in the Axios request configuration. The cancelRequest function calls the abort method on the controller to cancel the ongoing request.

The axios.isCancel method checks if the error is a cancellation error. If the request is canceled, a message is logged to the console; otherwise, the error is logged.

This approach allows you to cancel requests and handle cancellations gracefully, improving the user experience.

Using Axios with Async/Await

The async and await keywords in JavaScript make it easier to work with promises and asynchronous code. When used with Axios, async and await can simplify your code and make it more readable.

Here’s an example of how to use async and await with Axios:

Using npm/yarn:

import axios from 'axios';

// Function to fetch data asynchronously
const fetchData = async () => {

	try {

		const response = await axios.get('/data');
		console.log('Data:', response.data);

	} catch (error) {
		console.error('Error fetching data:', error);
	}
};

// Function to send data asynchronously
const postData = async () => {

	try {

		const response = await axios.post('/submit', {
			name: 'Edward Nyirenda Jr.',
			email: 'edward@coderscratchpad'
		});

		console.log('Response data:', response.data);

	} catch (error) {
		console.error('Error posting data:', error);
	}
};

// Call the functions to fetch and send data
fetchData();
postData();

Using CDN:

<script>

	// Function to fetch data asynchronously
	const fetchData = async () => {

		try {

			const response = await axios.get('/data');
			console.log('Data:', response.data);

		} catch (error) {
			console.error('Error fetching data:', error);
		}
	};

	// Function to send data asynchronously
	const postData = async () => {

		try {

			const response = await axios.post('/submit', {
				name: 'Edward Nyirenda Jr.',
				email: 'edward@coderscratchpad'
			});

			console.log('Response data:', response.data);

		} catch (error) {
			console.error('Error posting data:', error);
		}

	};

	// Call the functions to fetch and send data
	fetchData();
	postData();
  
</script>

In this example, we define two functions, fetchData and postData, to demonstrate making GET and POST requests asynchronously using async and await. The await keyword pauses the execution of the function until the promise is resolved, making the code more synchronous and easier to understand.

Using async and await with Axios enhances the readability of your code and makes it easier to handle asynchronous operations.

Conclusion

In this article, we explored the various features and functionalities of Axios, a promise-based HTTP client for JavaScript. We covered the basics of setting up Axios, making GET and POST requests, handling responses and errors, using interceptors, cancelling requests, and working with async/await.

The examples and concepts discussed provide a solid foundation for working with Axios in your projects. However, there is much more to explore. I encourage you to experiment further with Axios, integrating it into your applications to handle API interactions efficiently and effectively.

Leave a Reply