
- ReactJS - Home
- ReactJS - Introduction
- ReactJS - Roadmap
- ReactJS - Installation
- ReactJS - Features
- ReactJS - Advantages & Disadvantages
- ReactJS - Architecture
- ReactJS - Creating a React Application
- ReactJS - JSX
- ReactJS - Components
- ReactJS - Nested Components
- ReactJS - Using Newly Created Components
- ReactJS - Component Collection
- ReactJS - Styling
- ReactJS - Properties (props)
- ReactJS - Creating Components using Properties
- ReactJS - props Validation
- ReactJS - Constructor
- ReactJS - Component Life Cycle
- ReactJS - Event management
- ReactJS - Creating an Event−Aware Component
- ReactJS - Introduce Events in Expense Manager APP
- ReactJS - State Management
- ReactJS - State Management API
- ReactJS - Stateless Component
- ReactJS - State Management Using React Hooks
- ReactJS - Component Life Cycle Using React Hooks
- ReactJS - Layout Component
- ReactJS - Pagination
- ReactJS - Material UI
- ReactJS - Http client programming
- ReactJS - Form Programming
- ReactJS - Controlled Component
- ReactJS - Uncontrolled Component
- ReactJS - Formik
- ReactJS - Conditional Rendering
- ReactJS - Lists
- ReactJS - Keys
- ReactJS - Routing
- ReactJS - Redux
- ReactJS - Animation
- ReactJS - Bootstrap
- ReactJS - Map
- ReactJS - Table
- ReactJS - Managing State Using Flux
- ReactJS - Testing
- ReactJS - CLI Commands
- ReactJS - Building and Deployment
- ReactJS - Example
- Hooks
- ReactJS - Introduction to Hooks
- ReactJS - Using useState
- ReactJS - Using useEffect
- ReactJS - Using useContext
- ReactJS - Using useRef
- ReactJS - Using useReducer
- ReactJS - Using useCallback
- ReactJS - Using useMemo
- ReactJS - Custom Hooks
- ReactJS Advanced
- ReactJS - Accessibility
- ReactJS - Code Splitting
- ReactJS - Context
- ReactJS - Error Boundaries
- ReactJS - Forwarding Refs
- ReactJS - Fragments
- ReactJS - Higher Order Components
- ReactJS - Integrating With Other Libraries
- ReactJS - Optimizing Performance
- ReactJS - Profiler API
- ReactJS - Portals
- ReactJS - React Without ES6 ECMAScript
- ReactJS - React Without JSX
- ReactJS - Reconciliation
- ReactJS - Refs and the DOM
- ReactJS - Render Props
- ReactJS - Static Type Checking
- ReactJS - Strict Mode
- ReactJS - Web Components
- Additional Concepts
- ReactJS - Date Picker
- ReactJS - Helmet
- ReactJS - Inline Style
- ReactJS - PropTypes
- ReactJS - BrowserRouter
- ReactJS - DOM
- ReactJS - Carousel
- ReactJS - Icons
- ReactJS - Form Components
- ReactJS - Reference API
- ReactJS Useful Resources
- ReactJS - Quick Guide
- ReactJS Cheatsheet
- Axios CheatSheet
- ReactJS - Useful Resources
- ReactJS - Discussion
Axios CheatSheet
This Axios cheatsheet is based on Axios and uses this widely popular HTTP client for making API requests in JavaScript. It describes installing Axios, and performing CRUD operations and also has advanced features such as request interceptors, authorization headers, and retry logic. You will also get to know how to set up global configurations, manage errors, transform requests and responses, and make simultaneous requests as well. For more detail on best practices when it comes to secure, dynamic, and modular API integration, check the document itself.
Table of Contents
- Introduction
- Installing and Basics
- CRUD Operations Using Axios
- Advanced Axios Features
- Headers and Authorization
- Handling Global Configuration
- Handling Multiple Requests Simultaneously
- Handling Errors Globally
Introduction
Axios. js is a light weight JavaScript library for making HTTP requests from the browser or Node. js. It makes API interactions quick by offering an easy-to-use promise-based syntax for making GET, POST, PUT, DELETE, and other HTTP methods. Axios reviews often commend its simple handling of JSON data, easy to manage request and response interceptors, and efficient error handling.
Installing and Basics
Install Axios using npm
npm install axios
Basic
import axios from 'axios'; const instance = axios.create({ baseURL: 'https://api.example.com', timeout: 1000, headers: { 'Authorization': 'Bearer token' } });
CRUD Operations Using Axios
GET Request
Fetches data from an API endpoint
axios.get('https://reqres.in/api/users?delay=2') .then(response => { console.log(response.data); }) .catch(error => { console.log("This is error: " + error.response); }) .finally(() => { // always executed });
POST Request
Sends data to an API endpoint
axios.post('https://reqres.in/api/users', { "name": "aman", "job": "it" }) .then(response => { console.log(response.data); }) .catch(error => { console.log(error.response); }) .finally(() => { // always executed });
PUT Request
Updates existing data on an API endpoint.
axios.put('https://reqres.in/api/users/2', { "name": "Raju", "job": "Dev Ops" }) .then(response => { console.log(response.data); }) .catch(error => { console.log(error.response); }) .finally(() => { // always executed });
DELETE Request
Deletes data from an API endpoint.
axios.delete('https://reqres.in/api/users?page=2') .then(response => { console.log(response.data); }) .catch(error => { console.log(error.response); }) .finally(() => { // always executed });
Requests with Authorization Headers
Sends requests with an authorization token.
axios.post('https://reqres.in/api/users', { "data": "somedata" }, { headers: { 'Authorization': 'Token' } }) .then(response => { console.log(response.data); }) .catch(error => { console.log(error.response); }) .finally(() => { // always executed });
Advanced Axios Features
Base URL Configuration
Set up a base URL for cleaner code.
axios.defaults.baseURL = 'https://api.example.com';
Handling Responses and Errors
Handle successful and error responses.
axios.get('/endpoint') .then(response => { console.log(response.data); }) .catch(error => { console.error("Error: ", error.message); });
Request and Response Interceptors
Modify requests and responses globally.
// Add a request axios.interceptors.request.use(config => { config.headers['Authorization'] = 'Bearer token'; return config; }, error => Promise.reject(error)); // Add a response axios.interceptors.response.use(response => response, error => { console.error("Global error: ", error.response); return Promise.reject(error); });
Custom Axios Instances
Create reusable instances with specific configurations.
const apiClient = axios.create({ baseURL: 'https://api.example.com', timeout: 2000 });
Retry Logic
Implement automatic retries using axios-retry.
import axiosRetry from 'axios-retry'; axiosRetry(axios, { retries: 3 });
Progress Tracking
Monitor file upload/download progress.
axios.post('/upload', formData, { onUploadProgress: progressEvent => { console.log(`Uploaded: ${(progressEvent.loaded / progressEvent.total) * 100}%`); } });
Request Cancellation
Cancel ongoing requests using CancelToken or AbortController.
const controller = new AbortController(); axios.get('/endpoint', { signal: controller.signal }) .catch(error => { if (error.name === 'CanceledError') { console.log('Request canceled'); } }); // Cancel the request controller.abort();
Timeouts
Set timeouts for requests.
axios.get('/endpoint', { timeout: 5000 }) .catch(error => { if (error.code === 'ECONNABORTED') { console.error('Request timed out'); } });
Query Parameters
Pass query strings in requests.
axios.get('/endpoint', { params: { id: 123, sort: 'desc' } });
Headers and Authorization
Authorization Header
axios.get('/user', { headers: { 'Authorization': 'Bearer YOUR_TOKEN' } }) .then(response => console.log(response.data)) .catch(error => console.error(error));
Custom Headers
axios.post('/submit', data, { headers: { 'Custom-Header': 'value' } }) .then(response => console.log(response.data)) .catch(error => console.error(error));
Handling Global Configuration
Set a Global Base URL −
axios.defaults.baseURL = 'https://api.example.com';
Set Global Headers
axios.defaults.headers.common['Authorization'] = 'Bearer YOUR_TOKEN';
Transforming Requests and Responses
Transforming Requests
axios.defaults.transformRequest = [(data) => { // Modify request data return JSON.stringify(data); }];
Transforming Responses
axios.defaults.transformResponse = [(data) => { // Modify response data return JSON.parse(data); }];
Handling Multiple Requests Simultaneously
axios.all([ axios.get('/user'), axios.get('/posts') ]) .then(axios.spread((userResponse, postsResponse) => { console.log(userResponse.data); console.log(postsResponse.data); })) .catch(error => console.error(error));
Handling Errors Globally
axios.interceptors.response.use( response => response, error => { if (error.response.status === 401) { console.log("Unauthorized: Redirecting to login..."); // Redirect or handle refresh token logic } else if (error.response.status === 500) { console.log("Server error, please try again later."); } return Promise.reject(error); } );