Chapter 4: Interceptor Mechanism
9/1/25About 2 min
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 Basic Concept of Interceptors
Interceptors are one of the core features of Axios, allowing you to intercept and modify requests or responses before they are handled.
Interceptor Workflow
// Request Interceptor -> Send Request -> Response Interceptor -> Return Result
const interceptorFlow = {
request: "Executes before the request is sent",
response: "Executes after the response is returned",
error: "Executes when an error occurs"
};
4.2 Request Interceptors
Basic Usage
// Add a request interceptor
axios.interceptors.request.use(
function (config) {
// Do something before request is sent
console.log('Sending request:', config);
// Add a timestamp
config.headers['X-Timestamp'] = Date.now();
// Add an 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 a response interceptor
axios.interceptors.response.use(
function (response) {
// Any status code that lies within the range of 2xx cause this function to trigger
console.log('Received response:', response.status);
// Unified handling of response data
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 codes that falls outside the range of 2xx cause this function to trigger
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 the interceptor ID
const requestInterceptor = axios.interceptors.request.use(config => config);
const responseInterceptor = axios.interceptors.response.use(response => response);
// Remove the interceptors
axios.interceptors.request.eject(requestInterceptor);
axios.interceptors.response.eject(responseInterceptor);
4.5 Practical Application Example
Complete Interceptor Configuration
class ApiInterceptors {
constructor(axiosInstance) {
this.axios = axiosInstance;
this.setupInterceptors();
}
setupInterceptors() {
// Request interceptor
this.axios.interceptors.request.use(
(config) => {
// Add 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, enabling:
- Unified request header management
- Automatic authentication handling
- Unified error handling
- Request and response data transformation
- Loading state management
Key Takeaways
- Interceptors are executed in the order they are added
- Request interceptors can modify the configuration
- Response interceptors can handle data and errors
- Proper use of interceptors can greatly simplify code
Next Chapter Preview
The next chapter will cover instantiation and global configuration, learning how to create multiple Axios instances to handle different API services.