Chapter 1: Getting Started with Axios

Haiyue
15min

Chapter 1: Getting Started with Axios

Learning Objectives

  1. Understand the concept and advantages of Axios
  2. Master Axios installation and basic configuration
  3. Learn to send simple HTTP requests
  4. Understand Promise and asynchronous programming basics
  5. Master basic error handling

1.1 What is Axios

Introduction to Axios

Axios is a Promise-based HTTP client library for browsers and Node.js environments. It is one of the most popular JavaScript HTTP request libraries currently available.

Main Features

// Core features of Axios
const axiosFeatures = {
  promise: "Promise-based, supports async/await",
  browser: "Supports browser environment",
  nodejs: "Supports Node.js environment",
  interceptors: "Request and response interceptors",
  transformation: "Automatic JSON data conversion",
  cancellation: "Request cancellation support",
  protection: "Client-side XSRF protection",
  timeout: "Request timeout configuration",
  wide_browser_support: "Wide browser compatibility"
};

Comparison with Other HTTP Libraries

// Comparison table
const comparison = {
  fetch: {
    pros: ["Native API", "Modern browser support", "Lightweight"],
    cons: ["Requires polyfill", "Complex error handling", "Lacks interceptors"]
  },
  xhr: {
    pros: ["Native support", "Full control"],
    cons: ["Complex API", "Callback hell", "Verbose code"]
  },
  axios: {
    pros: ["Promise support", "Interceptors", "Auto conversion", "Error handling", "Request cancellation"],
    cons: ["Requires additional dependency", "Relatively larger bundle size"]
  }
};

1.2 Installing and Importing Axios

NPM Installation

# Install using npm
npm install axios

# Install using yarn
yarn add axios

# Install using pnpm
pnpm add axios

CDN Import

<!-- Import via CDN -->
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

<!-- Or use unpkg -->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

Module Import

// ES6 module import
import axios from 'axios';

// CommonJS import
const axios = require('axios');

// On-demand import
import { get, post } from 'axios';

1.3 Basic Usage

Sending GET Requests

// Simplest GET request
axios.get('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => {
    console.log('Data:', response.data);
    console.log('Status:', response.status);
    console.log('Headers:', response.headers);
  })
  .catch(error => {
    console.error('Error:', error);
  });

// Using async/await
async function fetchPost() {
  try {
    const response = await axios.get('https://jsonplaceholder.typicode.com/posts/1');
    console.log(response.data);
  } catch (error) {
    console.error('Request failed:', error);
  }
}

Sending POST Requests

// POST request sending data
const postData = {
  title: 'Hello World',
  body: 'This is a test post',
  userId: 1
};

axios.post('https://jsonplaceholder.typicode.com/posts', postData)
  .then(response => {
    console.log('Created successfully:', response.data);
    console.log('Status code:', response.status);
  })
  .catch(error => {
    console.error('Creation failed:', error);
  });

// Using async/await
async function createPost() {
  try {
    const response = await axios.post(
      'https://jsonplaceholder.typicode.com/posts',
      {
        title: 'New Post',
        body: 'Post content',
        userId: 1
      }
    );
    console.log('New article:', response.data);
  } catch (error) {
    console.error('Creation failed:', error);
  }
}

Using Configuration Objects

// Using complete configuration object
const config = {
  method: 'get',
  url: 'https://jsonplaceholder.typicode.com/posts',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer your-token'
  },
  timeout: 5000,
  params: {
    userId: 1,
    _limit: 10
  }
};

axios(config)
  .then(response => {
    console.log('Request with config successful:', response.data);
  })
  .catch(error => {
    console.error('Request with config failed:', error);
  });

1.4 Promise Basics Review

Promise Concept

// Three states of Promise
const promiseStates = {
  pending: "Pending - initial state",
  fulfilled: "Fulfilled - operation successful",
  rejected: "Rejected - operation failed"
};

// Basic Promise usage
const myPromise = new Promise((resolve, reject) => {
  // Asynchronous operation
  setTimeout(() => {
    const success = Math.random() > 0.5;
    if (success) {
      resolve('Operation successful');
    } else {
      reject('Operation failed');
    }
  }, 1000);
});

myPromise
  .then(result => console.log(result))
  .catch(error => console.error(error));

async/await Syntax

// async/await makes asynchronous code look synchronous
async function fetchUserData(userId) {
  try {
    // Wait for Promise to complete
    const userResponse = await axios.get(`/api/users/${userId}`);
    const user = userResponse.data;

    // Can wait for multiple Promises sequentially
    const postsResponse = await axios.get(`/api/users/${userId}/posts`);
    const posts = postsResponse.data;

    return {
      user,
      posts,
      totalPosts: posts.length
    };
  } catch (error) {
    console.error('Failed to fetch user data:', error);
    throw error; // Re-throw error
  }
}

// Using async function
fetchUserData(1)
  .then(data => console.log('User info:', data))
  .catch(error => console.error('Processing failed:', error));

1.5 Response Structure Explained

Response Object Structure

// Complete structure of Axios response object
axios.get('/api/users/1')
  .then(response => {
    console.log('Response data:', response.data);        // Server response data
    console.log('Status code:', response.status);         // HTTP status code
    console.log('Status text:', response.statusText);     // HTTP status text
    console.log('Response headers:', response.headers);   // Response headers object
    console.log('Request config:', response.config);      // Request configuration
    console.log('Request object:', response.request);     // Request object
  });

// Extract needed data using destructuring
axios.get('/api/users/1')
  .then(({ data, status, headers }) => {
    console.log('Only care about this data:', { data, status, headers });
  });

Status Code Handling

// Handle different scenarios based on status code
async function handleResponse(url) {
  try {
    const response = await axios.get(url);

    switch (response.status) {
      case 200:
        console.log('Request successful:', response.data);
        break;
      case 201:
        console.log('Creation successful:', response.data);
        break;
      case 204:
        console.log('Deletion successful, no content returned');
        break;
      default:
        console.log('Other success status:', response.status);
    }

    return response.data;
  } catch (error) {
    // Handle error status codes
    if (error.response) {
      const { status, data } = error.response;
      switch (status) {
        case 400:
          console.error('Request parameter error:', data);
          break;
        case 401:
          console.error('Unauthorized access:', data);
          break;
        case 404:
          console.error('Resource not found:', data);
          break;
        case 500:
          console.error('Internal server error:', data);
          break;
        default:
          console.error('Other error:', status, data);
      }
    }
    throw error;
  }
}

1.6 Basic Error Handling

Error Type Classification

// Complete example of Axios error handling
async function robustRequest(url) {
  try {
    const response = await axios.get(url);
    return response.data;
  } catch (error) {
    if (error.response) {
      // Server responded with error status code
      console.error('Response error:', {
        status: error.response.status,
        data: error.response.data,
        headers: error.response.headers
      });

      // Different handling based on error type
      if (error.response.status >= 500) {
        console.error('Server error, please try again later');
      } else if (error.response.status >= 400) {
        console.error('Client error, please check request');
      }
    } else if (error.request) {
      // Request was sent but no response received
      console.error('Network error:', error.request);
      console.error('Possible network connection issue or server not responding');
    } else {
      // Error occurred while setting up request
      console.error('Request configuration error:', error.message);
    }

    // General error information
    console.error('Complete error info:', error.config);
    throw error;
  }
}

Error Retry Mechanism

// Simple retry mechanism
async function requestWithRetry(url, maxRetries = 3) {
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      const response = await axios.get(url);
      return response.data;
    } catch (error) {
      console.log(`Attempt ${attempt} failed`);

      // Last attempt failed, throw error
      if (attempt === maxRetries) {
        throw error;
      }

      // Wait before retrying
      await new Promise(resolve => setTimeout(resolve, 1000 * attempt));
    }
  }
}

// Using retry mechanism
requestWithRetry('https://jsonplaceholder.typicode.com/posts/1')
  .then(data => console.log('Successfully retrieved data:', data))
  .catch(error => console.error('Still failed after multiple retries:', error));

1.7 Practice Exercises

Exercise 1: Basic Requests

// Exercise: Fetch and display user list
async function getUserList() {
  try {
    const response = await axios.get('https://jsonplaceholder.typicode.com/users');
    const users = response.data;

    console.log(`Retrieved ${users.length} users:`);
    users.forEach(user => {
      console.log(`- ${user.name} (${user.email})`);
    });

    return users;
  } catch (error) {
    console.error('Failed to get user list:', error);
    return [];
  }
}

getUserList();

Exercise 2: POST Request to Create Resource

// Exercise: Create new user
async function createUser(userData) {
  try {
    const response = await axios.post('https://jsonplaceholder.typicode.com/users', {
      name: userData.name,
      email: userData.email,
      phone: userData.phone
    });

    console.log('User created successfully:', response.data);
    return response.data;
  } catch (error) {
    console.error('Failed to create user:', error);
    throw error;
  }
}

// Test creating user
createUser({
  name: 'John Doe',
  email: 'john@example.com',
  phone: '123-456-7890'
});

Exercise 3: Comprehensive Application

// Exercise: User management system
class UserManager {
  constructor() {
    this.baseURL = 'https://jsonplaceholder.typicode.com';
  }

  // Get all users
  async getAllUsers() {
    try {
      const response = await axios.get(`${this.baseURL}/users`);
      return response.data;
    } catch (error) {
      console.error('Failed to get user list:', error);
      return [];
    }
  }

  // Get single user
  async getUser(id) {
    try {
      const response = await axios.get(`${this.baseURL}/users/${id}`);
      return response.data;
    } catch (error) {
      console.error(`Failed to get user ${id}:`, error);
      return null;
    }
  }

  // Create user
  async createUser(userData) {
    try {
      const response = await axios.post(`${this.baseURL}/users`, userData);
      console.log('User created successfully:', response.data);
      return response.data;
    } catch (error) {
      console.error('Failed to create user:', error);
      throw error;
    }
  }

  // Update user
  async updateUser(id, userData) {
    try {
      const response = await axios.put(`${this.baseURL}/users/${id}`, userData);
      console.log('User updated successfully:', response.data);
      return response.data;
    } catch (error) {
      console.error(`Failed to update user ${id}:`, error);
      throw error;
    }
  }

  // Delete user
  async deleteUser(id) {
    try {
      await axios.delete(`${this.baseURL}/users/${id}`);
      console.log(`User ${id} deleted successfully`);
      return true;
    } catch (error) {
      console.error(`Failed to delete user ${id}:`, error);
      return false;
    }
  }
}

// Using user management system
async function testUserManager() {
  const userManager = new UserManager();

  // Get all users
  const users = await userManager.getAllUsers();
  console.log('All users:', users.length);

  // Get specific user
  const user = await userManager.getUser(1);
  console.log('User 1:', user?.name);

  // Create new user
  const newUser = await userManager.createUser({
    name: 'Test User',
    email: 'test@example.com'
  });
}

testUserManager();

Chapter Summary

In Chapter 1, we learned:

  1. Axios Concepts and Advantages: Understood the core features and advantages of Axios as an HTTP client
  2. Installation and Import: Mastered various methods to install and import Axios
  3. Basic Usage: Learned to send basic HTTP requests such as GET and POST
  4. Promise Basics: Reviewed the usage of Promise and async/await
  5. Response Handling: Understood the structure of Axios response objects and data extraction
  6. Error Handling: Mastered basic error handling and retry mechanisms

These fundamentals lay a solid foundation for further in-depth learning of Axios’s advanced features. In the next chapter, we will learn in detail about the usage of various HTTP request methods.

Key Points

  • Axios is a Promise-based HTTP client that supports both browsers and Node.js
  • Using async/await can make asynchronous code more concise and readable
  • Proper error handling is key to building stable applications
  • Response objects contain important information like data, status, headers
  • Practice is the best way to master Axios

Next Chapter Preview

The next chapter will dive into HTTP request methods, including detailed usage of GET, POST, PUT, DELETE and other methods, as well as parameter passing and data format handling.