Chapter 4: Interceptor Mechanism
Haiyue
5min
Chapter 4: Interceptor Mechanism
Learning Objectives
- Understand the concept and role of interceptors
- Master the use of request interceptors
- Learn to configure response interceptors
- Implement unified error handling
- Master dynamic management of interceptors
4.1 Interceptor Basic Concepts
Interceptors are one of Axios’s core features, allowing requests or responses to be intercepted and modified before they are processed.
Interceptor Workflow
// Request Interceptor -> Send Request -> Response Interceptor -> Return Result
const interceptorFlow = {
request: "Execute before sending request",
response: "Execute after receiving response",
error: "Execute when error occurs"
};
4.2 Request Interceptors
Basic Usage
// Add request interceptor
axios.interceptors.request.use(
function (config) {
// Do something before sending request
console.log('Sending request:', config);
// Add timestamp
config.headers['X-Timestamp'] = Date.now();
// Add authentication token
const token = localStorage.getItem('token');
if (token) {
config.headers['Authorization'] = `Bearer ${token}`;
}
return config;
},
function (error) {
// Do something with request error
console.error('Request configuration error:', error);
return Promise.reject(error);
}
);
4.3 Response Interceptors
Basic Usage
// Add response interceptor
axios.interceptors.response.use(
function (response) {
// Any status code within the 2xx range triggers this function
console.log('Received response:', response.status);
// Unified response data handling
if (response.data && response.data.code !== undefined) {
if (response.data.code !== 200) {
throw new Error(response.data.message || 'Request failed');
}
return response.data.data;
}
return response;
},
function (error) {
// Any status code outside the 2xx range triggers this function
console.error('Response error:', error);
if (error.response?.status === 401) {
// Clear token and redirect to login page
localStorage.removeItem('token');
window.location.href = '/login';
}
return Promise.reject(error);
}
);
4.4 Interceptor Management
Removing Interceptors
// Save interceptor ID
const requestInterceptor = axios.interceptors.request.use(config => config);
const responseInterceptor = axios.interceptors.response.use(response => response);
// Remove interceptors
axios.interceptors.request.eject(requestInterceptor);
axios.interceptors.response.eject(responseInterceptor);
4.5 Practical Application Examples
Complete Interceptor Configuration
class ApiInterceptors {
constructor(axiosInstance) {
this.axios = axiosInstance;
this.setupInterceptors();
}
setupInterceptors() {
// Request interceptor
this.axios.interceptors.request.use(
(config) => {
// Show loading
this.showLoading();
// Add authentication header
const token = this.getToken();
if (token) {
config.headers['Authorization'] = `Bearer ${token}`;
}
return config;
},
(error) => {
this.hideLoading();
return Promise.reject(error);
}
);
// Response interceptor
this.axios.interceptors.response.use(
(response) => {
this.hideLoading();
return response;
},
(error) => {
this.hideLoading();
this.handleError(error);
return Promise.reject(error);
}
);
}
getToken() {
return localStorage.getItem('token');
}
showLoading() {
// Show loading state
}
hideLoading() {
// Hide loading state
}
handleError(error) {
if (error.response?.status === 401) {
this.handleUnauthorized();
} else if (error.response?.status >= 500) {
this.showErrorMessage('Server error, please try again later');
}
}
handleUnauthorized() {
localStorage.removeItem('token');
window.location.href = '/login';
}
showErrorMessage(message) {
console.error(message);
}
}
Chapter Summary
Interceptors are one of Axios’s most powerful features, capable of implementing:
- Unified request header management
- Automatic authentication handling
- Unified error handling
- Request and response data transformation
- Loading state management
Key Points
- Interceptors execute in the order they are added
- Request interceptors can modify configuration
- Response interceptors can handle data and errors
- Proper use of interceptors can greatly simplify code
Next Chapter Preview
The next chapter will learn about instantiation and global configuration, understanding how to create multiple Axios instances to handle different API services.