API Request Tool and Encapsulation
Table of Contents
- Introduction
- Project Architecture Overview
- Core Request Tool Analysis
- Interceptor Chain Details
- Permission and State Management Integration
- Error Handling Mechanism
- Performance Optimization Strategy
- Usage Examples and Best Practices
- Troubleshooting Guide
- Conclusion
Introduction
The API request tool layer in the lmes-web-base project is a highly encapsulated axios instance that provides a complete HTTP request solution. This tool layer is not only responsible for basic network communication, but also integrates advanced features such as permission verification, state management, error handling, and loading status, providing unified and powerful API access capabilities for the entire application.
Core features include:
- Automated Authorization header injection
- Content-Type standardization
- Environment-adaptive baseURL configuration
- Support for credentials (withCredentials)
- Request interceptors integrating permission verification and loading state management
- Response interceptors uniformly handling various error scenarios
- Support for cancelling requests (CancelToken)
- Data preprocessing and transformation mechanism
- Internationalized error message support
Project Architecture Overview
Diagram sources
Core Request Tool Analysis
axios Instance Configuration
// baseURL environment adaptation
let baseURL = ''
const params = new URLSearchParams(location.search)
baseURL = baseURL || params.get('baseURL') || ''
console.info('[baseURL]', baseURL)
// axios instance creation
const service = axios.create({
baseURL,
headers: {},
})
Core configuration features:
- Dynamic baseURL adaptation: Supports passing baseURL via URL parameters to achieve multi-environment deployment
- Simplified default configuration: Removed hardcoded configurations such as timeout to maintain flexibility
- Empty headers initialization: Avoid default values interfering with custom configurations
Automated Header Management
function appendHeaders(headers = {}) {
function withDefaultHeaders(headers: Record<string, any>) {
const token = Session.get('Token')
const defaultHeaders = {
'Content-Type': 'application/json;charset=UTF-8',
'X-Project': Session.get('X-Project'),
'X-Client-Id': localStorage.getItem('clientId'),
get Authorization() {
return token ? `Bearer ${token}` : undefined
},
get environment() {
return window.app.running ? 'runningtime' : undefined
},
get ['Accept-Language']() {
try {
return Language.getLangReqHeader()
} catch (error) {
return undefined
}
},
}
return Object.assign({}, defaultHeaders, headers)
}
return withDefaultHeaders(headers)
}
Section sources
Interceptor Chain Details
Request Interceptor Flow
Diagram sources
Core responsibilities of request interceptors:
- Loading State Management: Control global loading indicator via counter
- Header Standardization: Automatically inject necessary authentication and project identifier information
- Data Formatting: Ensure JSON data is correctly serialized
- Silent Mode Support: Allow disabling loading state and error prompts
Response Interceptor Processing Flow
Diagram sources
Section sources
Permission and State Management Integration
Permission System Integration
Diagram sources
Storage System Collaboration
// Local storage encapsulation
const Local = {
set(key: string, val: any) {
window.localStorage.setItem(key, JSON.stringify(val))
},
get(key: string) {
const value: null | string = window.localStorage.getItem(key) || null
if (!value) return null
return JSON.parse(value)
},
// ... other methods
}
// Session storage encapsulation
const Session = {
set(key: string, val: any) {
window.sessionStorage.setItem(key, JSON.stringify(val))
},
get(key: string) {
const value: null | string = window.sessionStorage.getItem(key)
try {
if (!value) return null
return JSON.parse(value)
} catch (error) {
return value
}
},
// ... other methods
}
Section sources
Error Handling Mechanism
Multi-level Error Handling
-
Authentication Error Handling
- 401/403 status code automatic detection
- Re-login popup mechanism
- Error suppression in silent mode
-
Business Error Handling
- Unified error message extraction
- Internationalized error prompts
- Special handling for file download errors
-
Network Error Handling
- Timeout, disconnection, and other network anomalies
- Request cancellation handling
- Proxy interface non-existence detection
Error Message Internationalization
const message =
data?.msg ||
data?.message ||
data?.title ||
data ||
statusText ||
msg ||
'Request Error'
const loginMessage = {
'401': Language._t('Login expired'),
'403': Language._t('Access denied'),
}[status]
Section sources
Performance Optimization Strategy
Loading State Optimization
// Smart loading state management
let reqNum: number = 0
let loadingInstance: LoadingInstance
let lastClickTime = Date.now()
const setLoading = (silent: boolean) => {
if (silent) return
reqNum++
if (reqNum === 1) {
loadingInstance = ElLoading.service({
...loadingOptions,
customClass: `${loadingOptions.customClass} ${
Date.now() - lastClickTime < 16 ? 'locked' : ''
}`,
})
}
}
const closeLoading = (silent: boolean) => {
if (silent) return
reqNum--
if (reqNum <= 0) {
reqNum = 0
loadingInstance && loadingInstance.close()
}
}
Request Merging and Caching Strategy
Although the current implementation mainly focuses on single request processing, it can be extended in the following ways:
- Request Deduplication: Based on URL and parameter uniqueness judgment
- Response Caching: Smart caching mechanism for GET requests
- Batch Requests: Support concurrent processing of multiple requests
Section sources
Usage Examples and Best Practices
Basic API Call
// Get project configuration
export const getProjectConfig = (name: string) => {
return request.get(`/projectApi/env?name=${name}`)
}
// Create component
export const createWidget = (data) => {
return request.post(`/projectApi/create`, data)
}
Advanced Configuration Usage
// Silent request (no loading state shown)
await request.get('/api/status', { silent: true })
// Silent error (no error prompt shown)
await request.get('/api/check', { unLogError: true })
// File upload
export const postImport = (file: FormData) => {
return request({
url: `/api/v1/zc/productsop/uploadsop`,
method: 'post',
contentType: 'multipart/form-data',
headers: { accept: '*/*' },
data: file,
})
}
Best Practice Suggestions
- Reasonable use of silent mode: For background tasks or scenarios with high user experience requirements
- Error handling strategy: Choose appropriate error handling methods according to business needs
- Request configuration reuse: Reduce repetitive configuration through inheritance and composition
- Performance monitoring: Use interceptors to record request performance metrics
Section sources
Troubleshooting Guide
Common Problem Diagnosis
-
Authentication Failure
- Check if Token is valid
- Verify if Authorization header is correctly injected
- Confirm user session status
-
Request Timeout
- Check network connection status
- Verify server response time
- Consider increasing timeout configuration
-
CORS Issues
- Confirm CORS configuration
- Check proxy settings
- Verify domain matching rules
-
Loading State Anomaly
- Check request counter logic
- Verify correct closing of asynchronous requests
- Confirm Element Plus loading component configuration
Debugging Tips
// Enable detailed logs
console.log('[Request Config]', config)
console.log('[Response Data]', response.data)
// Error tracing
const reason = new Error(`Request Error ${status} ${method} ${url}`)
return Promise.reject(reason)
Conclusion
The API request tool layer of lmes-web-base demonstrates best practices for HTTP request processing in modern frontend applications. Through highly abstract and modular design, it successfully encapsulates complex network communication logic into simple and easy-to-use interfaces while maintaining enough flexibility to adapt to different business needs.
Core Advantages
- Unified Error Handling: Consistent error handling strategy implemented through response interceptors
- Intelligent Loading Management: Global loading state control based on request counting
- Perfect Permission Integration: Seamless integration with permission management system
- Internationalization Support: Complete multi-language error message processing
- Extensible Design: Clear architecture facilitates functional extension
Technical Highlights
- Interceptor Chain Pattern: Implements unified processing of requests and responses
- Dynamic Configuration Mechanism: Supports flexible configuration adjustments at runtime
- State Management Integration: Deep integration with Vue state management system
- Performance Optimization Consideration: Intelligent loading state management and resource release
This API request tool layer not only meets current project functional requirements but also lays a solid foundation for future functional expansion and technological evolution. Through continuous optimization and improvement, it will continue to provide stable and reliable network communication capabilities for the entire application.