What is Axios?
Axios is a promise-based HTTP client for the browser, and Node.js allows you to send HTTP requests to communicate with an API. It is lightweight, easy to use, and supports most standard HTTP methods such as GET, POST, PUT, and DELETE. Its popularity derives from flexibility, in-built error handling, and simplicity of use.
Key Features of Axios
Here are the key features of axios react.js:
- Promise-based: A promise-based way to deal with asynchronous operations.
- Error handling: It allows you to manage your error using a uniform structure.
- Interceptors: Interceptors allow global interception of requests and responses for all HTTP callings.
- Cancellation: Axios includes built-in support for cancelling requests.
- Automatic JSON parsing: Automatically parses the JSON response from APIs.
Need of Axios in React
Here are the reasons why Axios is required in React:
- Automatic parsing of JSON: Axios automatically parses the response data in JSON format. This leads to reduced manual parsing and thus simplifies the work done with the data returned by the API.
- Built-In CSRF Protection: Axios has built-in Cross-Site Request Forgery (CSRF) protection support, allowing you to set headers like X-CSRF-Token for added security easily.
- Request & Response Interceptors: Axios allows to define of interceptors for both requests and responses, making it easier in a single place to modify the requests, deal with errors, and properly apply formatting to the response.
- Simplified Error Handling: Axios has a clean way of handling errors through .catch(), allowing developers ease in managing errors centrally across API requests.
- Promise and Async/Await Support: Axios is fully compatible with Promises and allows you to use Async/Await syntax, thus making it easier to deal with asynchronous tasks and read the code in React components more easily.
Steps to Use Axios in React
To use react axios, you need to follow these steps:
Step 1: Installation of Axios
The installation methods for Axios using various package managers and CDNs:
1. Using jsDelivr CDN
To use Axios via jsDelivr CDN, include the following script tag in your HTML file:
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
This will load Axios into your browser, and you can use it directly in your JavaScript code.
2. Using unpkg CDN
To use Axios via unpkg CDN, include this script tag in your HTML file:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
This will also load Axios; you can use it directly in your JavaScript code.
3. Using npm(Node.js environment)
If you're using Node.js, you can install Axios using npm:
npm install axios
Once installed, you can import Axios in your JavaScript file:
const axios = require('axios');
4. Using yarn(Node.js environment)
If you're using Yarn, you can install Axios with the following command:
yarn add axios
Once installed, you can import Axios in your JavaScript file:
import axios from 'axios';
5. Using Bower
If you're using Bower for front-end package management, you can install Axios using:
bower install axios --save
This will add Axios to your bower_components directory, and you can include it in your HTML file:
<script src="bower_components/axios/dist/axios.min.js"></script>
Step 2: Initialize React Project
To begin, create a new React project in your desired folder. Use the following command to initialise a new React app:
npx create-react-app myreactapp
This command will create a new directory called myreactapp and set up all the necessary files for a React project.
Step 3: Move to Project Directory
Once the project is initialised, navigate to the project directory. You can do this by running the following command:
cd myreactapp
This will take you to the root folder of your React project, where all the files and dependencies are located.
Step 4: Add Axios as Dependency
Axios is an external library used for making HTTP requests and must be installed in your project. To install Axios, run the following command:
npm install axios
This will install the Axios library and add it to your node_modules folder and the dependencies section in your package.json file.
"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"axios": "^1.6.2",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}
Now, Axios is available for use within your React project.
Step 5: Implement Axios in Your Project
After setting up Axios, you can integrate it into your React components to make API calls. Here’s an example of how you might use Axios to upload files to a backend server.
Example: File Upload with Axios react.js
// Filename - App.js
import React from "react";
import axios from "axios";
class App extends React.Component {
state = {
selectedFiles: null, // Stores the selected files for upload
};
// Handles the file selection
handleFileSelection(e) {
const selectedFiles = e.target.files;
this.setState({ selectedFiles });
}
// Handles file upload via POST request
handleFileUpload(e) {
const { selectedFiles } = this.state;
let formData = new FormData();
// Appending the selected files to the form data object
Array.from(selectedFiles).forEach(file => {
formData.append("image", file);
});
formData.append("name", "User's File");
// Axios POST request to upload the files
axios({
url: "http://localhost:8080/upload", // API endpoint
method: "POST",
headers: {
// Optional: Add authorization token if needed
"Authorization": "Bearer your_token_here",
},
data: formData, // Sending form data with the request
})
.then((response) => {
console.log("Files uploaded successfully:", response.data);
})
.catch((error) => {
console.error("Error uploading files:", error);
});
}
render() {
return (
<div>
<h1>Upload Your Files</h1>
<input
type="file"
multiple // Allowing multiple file selection
onChange={(e) => this.handleFileSelection(e)} // Handle file selection
/>
<button onClick={(e) => this.handleFileUpload(e)}>
Upload Files
</button>
</div>
);
}
}
export default App;
Explanation
In the above program, users of the React component may choose multiple files to be stored in the state using the input field. Then, clicking on the upload files button sends them via an Axios POST request to a backend server using FormData. The server will log the response and, if errors arise, will catch and log them.
Step 6: Run the Application
After implementing Axios in your project, run the application with the following command:
npm start
This will start the development server, and you can view the application in your browser by navigating to:
http://localhost:3000/
You will see the file upload interface, and once the user selects files and clicks the upload button, the files will be sent to the backend API.
API Calls in React.js Using Axios
When working with Axios in React, you’ll typically make API calls using hooks like useEffect for functional components.
1. Using a GET Request with Axios
To make an API request and retrieve data, you can use the GET method in Axios.
axios.get('https://api.example.com/data')
.then(response => {
console.log(response.data); // Handle the API data
})
.catch(error => {
console.error('Error fetching data:', error); // Handle errors
});
Explanation
This is a basic API call in React.js, which uses Axios. It could be the URL of the endpoint of any API from which you want to retrieve data.
Output
On Success:
// Assuming response contains this JSON data
{ "id": 1, "name": "Resource" }
Console Output:
{ "id": 1, "name": "Resource" }
On Error:
Error fetching data: [error details]
2. Using the POST Method with Axios
Sending data to an API can be accomplished using Axios with the POST Method. This is an example of how to implement the axios post method in in react.js:
axios.post('https://api.example.com/submit', {
data: 'example data'
})
.then(response => {
console.log(response.data); // Handle the response data
})
.catch(error => {
console.error('Error submitting data:', error); // Handle errors
});
Explanation
A POST request sends data (e.g., { data: 'example data' }) to the API. The server's response is captured in response.data, while errors are handled in the catch block.
Output
On Success:
// Example of successful response:
{ "status": "success", "message": "Data submitted successfully" }
Console Output:
{ "status": "success", "message": "Data submitted successfully" }
On Error:
Error submitting data: [error details]
Key Differences Between the GET and POST methods
Here are the key differences for GET and POST methods such as:
Criteria |
GET |
POST |
Use cases |
Retrieving data (for example, search, navigation) |
Submitting data (for example, form submissions, file uploads) |
Idempotent |
Yes (repeated requests yield the same result) |
No (repeated requests may have different results) |
Caching |
Can be cached, stored in browser history |
Can never be cached |
Data transfer |
Information sent through URL (the query string) |
Information sent through the request body |
Purpose |
Retrieve/read data |
Create/update data |
Length of data |
Limited by URL length restrictions |
Very few restrictions |
Browser display |
Data is in the browser history |
Data is not in the browser history |
Use in URLs |
Can be bookmarked and included in links |
Cannot be bookmarked, no URL-based |
Error handling |
Error is shown in the URL |
The server usually handles errors |
Performance |
Faster during data retrieval |
A bit slow during large data submission |
3. Using a PUT Request with Axios
The PUT request is typically used for updating existing resources on the server.
const axios = require('axios');
axios.put('https://api.example.com/resource/1', {
data: {
name: 'Updated Resource',
description: 'This is an updated resource.'
}
})
.then(response => {
console.log('Updated resource:', response.data);
})
.catch(error => {
console.error('Error updating resource:', error);
});
Explanation
In the PUT request, we provide the resource ID in the URL and the new data in the body.
Output
If the PUT request is successful, you'll see the updated resource data printed in the console:
Updated resource: { "id": 1, "name": "Updated Resource", "description": "This is an updated resource." }
If an error occurs, such as the resource not being found or a network issue, you'll see an error message:
Error updating resource: Error: Request failed with status code 40
4. Using a DELETE Request with Axios
The DELETE request is used to delete an existing resource on the server.
const axios = require('axios');
axios.delete('https://api.example.com/resource/1')
.then(response => {
console.log('Deleted resource:', response.data);
})
.catch(error => {
console.error('Error deleting resource:', error);
});
Explanation
In the DELETE request, we provide the resource ID in the URL to specify which resource to delete.
Output
If the DELETE request is successful, you will see a confirmation of the deleted resource:
Deleted resource: { "message": "Resource deleted successfully" }
If the resource doesn’t exist or there’s a network issue, you will see an error message:
Error deleting resource: Error: Request failed with status code 404
5. Using Async and Await
Instead of chaining .then() and .catch(), use async/await for cleaner, more readable code. This approach makes it easier to handle asynchronous logic.
const fetchData = async () => {
try {
const response = await axios.get('https://api.example.com/endpoint');
console.log(response.data);
} catch (error) {
console.error('Error:', error);
}
};
Explanation
Using await axios.get() waits for the response from the API request before continuing execution. Try/catch handles success and errors using .then() and .catch().
Output
If the request is successful, you'll see the data from the API:
{ "id": 1, "name": "Resource", "description": "This is a resource." }
If there’s an error (e.g., network issue), you'll see:
Error: Error: Request failed with status code 404
6. Handling API Responses and Errors in Axios
Let’s understand how Axios simplifies managing successful and failed requests in a React application such as:
Handling Responses
When a promise is made within an API using Axios, the code inside .then() is activated in response to the promise. There are three types of useful information contained in the response: status, data, and headers, for example:
axios.get('https://api.example.com/data')
.then(response => {
console.log('Data:', response.data);
console.log('Status:', response.status);
})
.catch(error => {
console.error('Error:', error);
});
Error Handling in Axios
Axios offers a versatile way to handle errors. In the event of an error occurring during an API request, the error object provides several properties to help you diagnose the issue:
axios.get('https://api.example.com/data')
.then(response => {
console.log(response.data);
})
.catch(error => {
if (error.response) {
console.error('Error response:', error.response);
} else if (error.request) {
console.error('No response received:', error.request);
} else {
console.error('Error:', error.message);
}
});
Explanation
The response.data holds the API's returned data while response. status provides the HTTP status code (e.g., 200 for success). The catch block handles errors like network issues or timeouts, ensuring proper error logging.
Output
On success, you'll get the response data and status:
Data: { "id": 1, "name": "Resource" }
Status: 200
On error, you can handle different types of errors:
Error: Error: Request failed with status code 500
7. Using Axios with React Hooks (Functional Components)
In React, functional components integrate Axios to make an API call; you can just use the use effect hook to fetch data once it's mounted.
Example: Fetching Data in React with Axios
import React, { useEffect, useState } from 'react';
import axios from 'axios';
const FetchData = () => {
const [data, setData] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
axios.get('https://api.example.com/data')
.then(response => {
setData(response.data); // Set data to state
})
.catch(error => {
setError(error.message); // Handle errors
});
}, []);
return (
<div>
{error ? <p>Error: {error}</p> : <pre>{JSON.stringify(data, null, 2)}</pre>}
</div>
);
};
export default FetchData;
Explanation
This is an example of making an API call in React.js using Axios in a functional component with state management for the response and errors.
Output
On success, the fetched data is displayed as JSON:
{
"id": 1,
"name": "Resource"
}
On error, an error message is shown:
Error: Error: Request failed with status code 404
8. Configuring Axios Within React
You can configure Axios to set global defaults such as base URLs, headers, and timeouts. You can also make similar requests multiple times more easily.
Example: Creating Axios Instance in React
import axios from 'axios';
const axiosInstance = axios.create({
baseURL: 'https://api.example.com',
timeout: 10000, // Set timeout for requests
headers: { 'Authorization': 'Bearer token' }
});
export default axiosInstance;
Explanation
This Axios example in React can now be used across different components. This can be used for API calls in various parts of the app.
Output
Axios requests made with this instance will automatically use the base URL and header:
axiosInstance.get('/data')
.then(response => {
console.log(response.data);
});
9. Using Axios Interceptors In React
You can use Axios interceptors to modify requests and responses globally before handling .then() or .catch(). This is particularly useful for authentication token handling, adding headers, or logging.
Request Interceptor Example:
axios.interceptors.request.use(request => {
request.headers['Authorization'] = 'Bearer token'; // Add authorization header
return request;
}, error => {
return Promise.reject(error);
});
Explanation
This interceptor adds an Authorization header with a Bearer token to every outgoing request. If an error occurs during request preparation, it's rejected with Promise.reject.
Output
For requests, every request will now include the Authorization header.
Response Interceptor Example:
axios.interceptors.response.use(response => {
// Process the response before passing it to the .then() handler
return response;
}, error => {
// Handle errors globally
console.error('Global error handler:', error);
return Promise.reject(error);
});
Explanation
The response interceptor allows the processing of the response before it reaches .then(). If an error occurs during the response, it logs globally and rejects the promise with Promise. Reject.
Output
For responses, errors will be globally logged, and you can modify or reject responses.
10. Cancel Axios Requests When Necessary
In cases where a request is no longer needed (e.g., a user navigates to another page before a request completes), you can cancel ongoing requests to avoid unnecessary network traffic. Axios supports request cancellation using a CancelToken.
const cancelTokenSource = axios.CancelToken.source();
axios.get('https://api.example.com/endpoint', {
cancelToken: cancelTokenSource.token
})
.then(response => {
console.log(response.data);
})
.catch(error => {
if (axios.isCancel(error)) {
console.log('Request canceled', error.message);
} else {
console.error(error);
}
});
// To cancel the request:
cancelTokenSource.cancel('Request cancelled by the user.');
Explanation
This code describes how to cancel an Axios request. It creates a CancelToken, attaches it to the request, and allows cancellation by calling cancelTokenSource.cancel(), handling cancellation errors appropriately.
Output
If the request is canceled, you will see:
Request canceled Request cancelled by the user.
If the request is not canceled and an error occurs:
Error: Error: Request failed with status code 404
Response Objects in Axios
When you make an HTTP request using Axios and send a request to the server, you receive a response object. This object is populated with key properties containing information about the request and the response.
The core properties of the response object include:
- data: Data returned by the server in response to your request. Axios automatically makes this available and returns it as a JavaScript object, provided the server sends a JSON response.
- status: HTTP status code as returned by the server. For example, 200 means success 404 means not found, etc.
- statusText: The status message corresponding to the HTTP status returned by the server. This message typically accompanies the status code (e.g., OK for a successful request).
- headers: This property contains the complete set of headers that were returned by the server in response to your request. These can be used for metadata, content type, authentication details, etc.
- config: The original request configurations, including any settings and parameters when sending the request. This information is useful when you need to revert to the original configuration.
- request: The XMLHttpRequest object used in the browser to make the request and give low-level details about the request.
Code Example (Axios Response)
import React, { useState, useEffect } from 'react';
import axios from 'axios';
const AxiosResponseExample = () => {
const [data, setData] = useState(null); // To store the fetched data
const [loading, setLoading] = useState(true); // To track loading state
const [error, setError] = useState(null); // To store any error that occurs
useEffect(() => {
// Axios GET request to fetch data from an API
axios.get('https://jsonplaceholder.typicode.com/posts')
.then((response) => {
// On success, we store the response data
console.log('Response:', response); // Full Axios response object
setData(response.data); // Axios response contains 'data' property with actual data
setLoading(false); // Set loading to false after data is fetched
})
.catch((error) => {
// On error, we log the error and set the error state
console.error('Error response:', error.response); // Server's response in case of error
console.error('Error message:', error.message); // Error message
setError(error.message); // Store the error message
setLoading(false); // Stop loading even in case of error
});
}, []); // Empty dependency array ensures the effect runs only once on mount
// Render UI based on loading, error, or data state
if (loading) {
return <div>Loading...</div>; // Display loading indicator
}
if (error) {
return <div>Error: {error}</div>; // Display error message
}
return (
<div>
<h1>Fetched Posts</h1>
<ul>
{data.map(post => (
<li key={post.id}>{post.title}</li> // Render fetched post titles
))}
</ul>
</div>
);
};
export default AxiosResponseExample;
Explanation
This React component uses Axios to fetch data from the jsonplaceholder API. It displays a loading message while fetching, shows an error message if an error occurs, and renders the list of post titles once the data is successfully fetched.
Output
While loading: Loading...
On error: Error: [error message]
On success: A list of post titles, e.g.,
Fetched Posts
- Post Title 1
- Post Title 2
- Post Title 3
Error Object
If there is a problem with the request, the promise returned by Axios will be rejected with an error object. This object contains the following properties:
- message: A description of the error or issue during the request.
- response: This property is an object containing the server's response, assuming it was received. This is useful for analysing the response data in the case of an error.
- request: The XMLHttpRequest object associated with the request might provide valuable information as to why the request might have been aborted.
- config: The original request configuration, which you can check and analyse to figure out the actual setting used for the request.
Key Features of Axios Library
A few of the compelling features that have made the Axios library so widely used in JavaScript applications for making HTTP requests are:
- Automatic Transformation in JSON: The request and response data in Axios are automatically converted into JSON format, thereby simplifying the work of developers when it comes to operating with APIs that output standard JSON responses.
- HTTP Request Support in Node.js: Axios is equally useful for hands-on HTTP requests from the browser and the Node.js server environments.
- XSRF Protection: Client-side attacker protection is one of the significant advantages Axios provides to the developer circle. Axios handles the management of the XSRF tokens through automatic placement in the request so that development is not challenging.
- Support for Promises: The Promise API makes life easy; one can manage async operations in code using the following syntax .then(), .catch(), or even async/await.
- Cancellation of Requests: This helps cancel requests if they are not required and saves client resources. Cancel the duplicate request if a user navigates away from the page before one of the requests gets completed.
Shortcut Methods in Axios
Here are the axios simplified methods such as:
1. axios.request(config): It is the base method for any HTTP call, where you can define configurations that suit your particular needs, such as URL, headers, data, etc.
2. axios.head(url[, config]): Sends a HEAD request to the specified URL. It's generally used to obtain some metadata without returning the response body. I would like to check out the headers.
3. axios.get(url[, config]): This method sends a GET request to the specified URL to retrieve data from the server. It is the most common HTTP method for retrieving information.
4. axios.post(url[, data[, config]]): Sends a POST request to the specified URL. It is used to send data to the server to create new resources or to submit form data.
5. axios.put(url[, data[, config]]): In general, PUT requests may be applied for most updates of resources already in place on a server. The new data is sent in the request's body.
6. axios.delete(url[, config]): Sends a DELETE request to the URL. Used generally for deleting the resources from the server, e.g., for deleting post accounts.
7. axios.options(url[, config]): OPTIONS requests server communications to check what HTTP methods and other options are supported. Useful for checking CORS settings.
8. axios.patch(url[, data[, config]]): Sends a PATCH request to the server to partially update a resource. It's similar but only replaces parts of a resource, modifying specific fields.
Conclusion
In conclusion, installing axios in react.js can efficiently enhance the performance of your application and facilitate API integration. From fundamental to advanced features like interceptors and request cancellation, axios provides flexibility and efficient data management. Axios with react gives your web application powerful API interaction capabilities.
Frequently Asked Questions
1. What is Axios used for in React?
Axios is a React-based HTTP client that can easily connect a React application to APIs or other backend services. It makes retrieving or submitting data easy when sending requests like GET, POST, PUT, and DELETE.
2. Why Axios is used?
Axios is used as it provides a simple interface for performing the HTTP requests; it automatically converts JSON data for our response, has request and response interceptors, can cancel requests, and handles errors in a better way, and that's what makes this a popular option to perform API calls in React.
3. What is Axios npm?
A Javascript library in npm allows developers to make HTTP requests using Axios. A promise-based HTTP client for the browser and node.js, it makes working with APIs easier.
4. Is Axios a REST API?
No, Axios is not a REST API. Instead, it is an HTTP client library that can interact with any REST API by making HTTP requests, such as GET, POST, PUT, or DELETE.