Axios Request
VTS provides a simple HTTP request module encapsulation based on Axios, offering unified interface invocation methods and response handling mechanisms.
Basic Configuration
The project creates an independent instance using axios
, located in request.ts
with the following basic configuration:
ts
const service: AxiosInstance = axios.create({
baseURL: import.meta.env.VITE_BASE_API,
timeout: 15000
})
baseURL
: API base path obtained from environment variablestimeout
: Request timeout set to 15 seconds
Request Interceptor
The request interceptor mainly handles the following:
Token Processing:
- Automatically adds
Authorization
token to requests (except login interface) token
is retrieved from Cookies
- Automatically adds
Data Format Conversion:
- Automatically converts request data from camelCase to snake_case
- FormData type data remains unconverted
ts
service.interceptors.request.use(request => {
const token = Cookie.get('token')
// Convert naming convention (exclude FormData)
if (!(request.data instanceof FormData)) {
request.data = decamelizeKeys(request.data)
}
request.params = decamelizeKeys(request.params)
// Add token (exclude login interface)
if (request.url !== '/login') {
request.headers.Authorization = token
}
return request
})
Response Interceptor
The response interceptor handles the following scenarios:
- Unified Response Data Structure:
ts
interface RespData<T> {
success?: boolean
errorCode?: number
error?: number | string | null
msg?: string
data?: T
[key: string]: any
}
Special Response Handling:
- Process binary data (Blob) responses
- Handle file downloads
- Automatically convert response data from snake_case to camelCase
Error Handling:
- HTTP status code error handling
- Network request failure handling
- Support for error redirection configuration
Error Codes
The system defines a unified error code message mapping:
Status Code | Description |
---|---|
200 | Request successful |
201 | Create or modify data successful |
400 | Bad request |
401 | Unauthorized (token/username/password error) |
403 | Forbidden |
404 | Resource not found |
500 | Server error |
502 | Gateway error |
503 | Service unavailable |
504 | Gateway timeout |
Utility Functions
File Download
Provides file download-related utility functions:
ts
// Download file
export function downloadFile(boldData: any, filename = 'test-filename', type: string) {
const blob = boldData instanceof Blob
? boldData
: new Blob([boldData], { type })
// ... download logic
}
// Process filename
function extractFileNameFromContentDispositionHeader(value: string) {
// ... filename extraction logic
}
Usage Examples
ts
// Regular request
const response = await service.get('/api/users')
// File download request
const fileResponse = await service.get('/api/download', {
responseType: 'blob'
})
// Request with redirection
const response = await service.get('/api/data', {
redirect: 'error-page'
})