# 说明
提示
下面仅演示了 TS 中 axios 封装的基础版本(axios 基础封装 + 响应结果类型处理),更多版本可以查看个人项目:
https://github.com/Lencamo/request-tools
# 1、结构:
├── services
├── index.ts
├── request # axios封装
│ ├── index.ts
│ └── config.ts
└── modules # api管理
├── cart.ts
└── products.ts
// @/services/index.ts
import RenRequest from './request/index'
import { BASE_URL, TIMEOUT } from './request/config'
export const testRequest = new RenRequest({
baseURL: BASE_URL,
timeout: TIMEOUT
})
export * from './modules/home'
# 2、axios 封装:
// @/services/request/config.ts
export const BASE_URL = 'http://codercba.com:8000'
export const TIMEOUT = 10000
// @/services/request/index.ts
import axios from 'axios'
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
class RenRequest {
instance: AxiosInstance
constructor(config: AxiosRequestConfig) {
this.instance = axios.create(config)
// 响应拦截
this.instance.interceptors.response.use(
(response: AxiosResponse) => {
return response
},
(error: any) => {
return error
}
)
}
request(config: AxiosRequestConfig): Promise<AxiosResponse> {
return this.instance.request(config)
}
get<T = any>(config: AxiosRequestConfig): Promise<AxiosResponse<T>> {
return this.request({ ...config, method: 'get' })
}
post<T = any>(config: AxiosRequestConfig): Promise<AxiosResponse<T>> {
return this.request({ ...config, method: 'post' })
}
}
export default RenRequest
# 3、api 管理:
// @/services/modules/home.ts
import { testRequest } from '../index'
import type { AxiosResponse } from 'axios'
/**
* response数据类型
* - 【默认为any】
*/
interface IHomeData {
data: any
returnCode: string
success: boolean
}
export function getHomeList(): Promise<AxiosResponse<IHomeData, any>> {
return testRequest.get<IHomeData>({
url: '/home/multidata'
})
}
# 4、使用
import { getHomeList } from './services/modules/home'
getHomeList().then((res) => {
console.log(res.data)
})
export {}