Chapter 1: Getting Started with Axios
9/1/25About 5 min
Chapter 1: Getting Started with Axios
Learning Objectives
- Understand the concept and advantages of Axios
- Master the installation and basic configuration of Axios
- Learn to send simple HTTP requests
- Understand the basics of Promises and asynchronous programming
- Master basic error handling
1.1 What is Axios
Introduction to Axios
Axios is a Promise-based HTTP client library for browser and Node.js environments. It is currently one of the most popular JavaScript HTTP request libraries.
Key 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 transformation",
cancellation: "Request cancellation support",
protection: "Client-side XSRF protection",
timeout: "Request timeout setting",
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", "Automatic transformation", "Error handling", "Request cancellation"],
cons: ["Requires extra dependency", "Relatively larger package size"]
}
};
1.2 Installation and Import
NPM Installation
# Install with npm
npm install axios
# Install with yarn
yarn add axios
# Install with 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>
Modular Import
// ES6 modular import
import axios from 'axios';
// CommonJS import
const axios = require('axios');
// Import as needed
import { get, post } from 'axios';
1.3 Basic Usage
Sending a GET Request
// 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 a POST Request
// Sending data with a POST request
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('Creation successful:', 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 post:', response.data);
} catch (error) {
console.error('Creation failed:', error);
}
}
Using a Configuration Object
// Using a full 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('Configuration request successful:', response.data);
})
.catch(error => {
console.error('Configuration request failed:', error);
});
1.4 Promise Basics Review
Promise Concept
// Three states of a Promise
const promiseStates = {
pending: "Pending - initial state",
fulfilled: "Fulfilled - operation succeeded",
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 like synchronous code
async function fetchUserData(userId) {
try {
// Wait for the 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 the error
}
}
// Using the 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
// Full structure of an 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
});
// Extracting required data using destructuring
axios.get('/api/users/1')
.then(({ data, status, headers }) => {
console.log('Only interested in this data:', { data, status, headers });
});
Status Code Handling
// Handling different cases 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) {
// Handling error status codes
if (error.response) {
const { status, data } = error.response;
switch (status) {
case 400:
console.error('Bad request:', 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) {
// The server responded with an error status code
console.error('Response error:', {
status: error.response.status,
data: error.response.data,
headers: error.response.headers
});
// Handle different error types
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 the request');
}
} else if (error.request) {
// The request was sent but no response was received
console.error('Network error:', error.request);
console.error('Could be a network connection issue or no server response');
} else {
// An error occurred during request setup
console.error('Request configuration error:', error.message);
}
// General error information
console.error('Full 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`);
// Throw error on the last attempt
if (attempt === maxRetries) {
throw error;
}
// Wait for a while before retrying
await new Promise(resolve => setTimeout(resolve, 1000 * attempt));
}
}
}
// Using the retry mechanism
requestWithRetry('https://jsonplaceholder.typicode.com/posts/1')
.then(data => console.log('Successfully fetched data:', data))
.catch(error => console.error('Still failed after multiple retries:', error));
1.7 Practical Exercises
Exercise 1: Basic Request
// Exercise: Get and display a list of users
async function getUserList() {
try {
const response = await axios.get('https://jsonplaceholder.typicode.com/users');
const users = response.data;
console.log(`Fetched ${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: Create Resource with POST Request
// Exercise: Create a 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 a 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 a 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 a 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 a 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 a 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 the 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 a specific user
const user = await userManager.getUser(1);
console.log('User 1:', user?.name);
// Create a new user
const newUser = await userManager.createUser({
name: 'Test User',
email: 'test@example.com'
});
}
testUserManager();
Chapter Summary
In Chapter 1, we learned:
- Axios Concepts and Advantages: Understood the core features and benefits of Axios as an HTTP client.
- Installation and Import: Mastered various methods for installing and importing Axios.
- Basic Usage: Learned to send basic HTTP requests like GET and POST.
- Promise Basics: Reviewed the usage of Promises and async/await.
- Response Handling: Understood the structure of the Axios response object and how to extract data.
- Error Handling: Mastered basic error handling and retry mechanisms.
This foundational knowledge provides a solid basis for in-depth learning of Axios's advanced features. In the next chapter, we will delve into the detailed usage of various HTTP request methods.
Key Takeaways
- 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.
- The response object contains important information like
data
,status
, andheaders
. - Practice is the best way to master Axios.
Next Chapter Preview
The next chapter will dive deep into HTTP request methods, including detailed usage of GET, POST, PUT, DELETE, as well as parameter passing and data format handling.