
TL;DR: Axios 封装的核心不是把 `get/post` 包一层,而是把“环境配置、实例级拦截器、全局拦截器、单次请求拦截器、Loading 状态、响应类型”放到清晰的层级里。源笔记给了一个基于 TypeScript、Axios、E
**TL;DR:**Axios 封装的核心不是把 get/post 包一层,而是把“环境配置、实例级拦截器、全局拦截器、单次请求拦截器、Loading 状态、响应类型”放到清晰的层级里。源笔记给了一个基于 TypeScript、Axios、Element Plus 的封装样例,本文把它整理成可落地的结构。
适合在 Vue + TypeScript 项目里需要统一管理接口请求的前端开发者。
如果你的项目只有几个接口,直接用 Axios 就够了。如果接口数量多、环境多、Loading 和错误处理规则多,封装才有价值。
Axios 支持多种调用方式:
axios(config)axios.request(config)axios.get(url[, config])axios.post(url[, data[, config]])axios.put(url[, data[, config]])axios.patch(url[, data[, config]])源笔记里真正需要封装的原因是:默认 Axios 实例只有一套默认配置,而项目里经常存在不同 baseURL、timeout、Content-Type 或不同拦截规则。
所以封装目标不是替代 Axios,而是为项目创建一个可控实例。
源笔记采用这样的目录:
service
├─ index.ts
└─ request
├─ index.ts
├─ config.ts
└─ type.ts
职责分别是:
service/index.ts:创建并导出请求实例。request/index.ts:定义 YCRequest 类。request/config.ts:按环境切换 BASE_URL 和 TIME_OUT。request/type.ts:扩展 Axios 类型,支持自定义拦截器和 showLoading。这个拆法的好处是:业务代码只从 service 进口拿实例,不需要知道封装内部怎么处理 Loading 和拦截器。
源笔记给出两类环境区分方式:根据 process.env.NODE_ENV 判断,或写不同 .env 文件。
代码版如下:
let BASE_URL = ''
const TIME_OUT = 1000
if (process.env.NODE_ENV === 'development') {
BASE_URL = 'http://123.207.32.32:8000/'
} else if (process.env.NODE_ENV === 'production') {
BASE_URL = 'http://lyc.org/prod'
} else if (process.env.NODE_ENV === 'test') {
BASE_URL = 'http://lyc.org/test'
}
export { BASE_URL, TIME_OUT }
这段代码的重点是集中出口。不要在页面组件里到处写接口域名,否则环境切换会变成全局搜索替换。
源笔记通过接口扩展 Axios 配置:
import type { AxiosRequestConfig, AxiosResponse } from 'axios'
export interface YCRequestInterceptors<T = AxiosResponse> {
requestInterceptor?: (config: AxiosRequestConfig) => AxiosRequestConfig
requestInterceptorCatch?: (error: any) => any
responseInterceptor?: (res: T) => T
responseInterceptorCatch?: (error: any) => any
}
export interface YCRequestConfig<T = AxiosResponse> extends AxiosRequestConfig {
interceptors?: YCRequestInterceptors<T>
showLoading?: boolean
}
这里加了两类能力:
interceptors:允许实例或单次请求注入拦截器。showLoading:允许单次请求控制是否显示 Loading。这个类型设计让封装保持开放,但没有引入新的依赖或复杂抽象。
YCRequest 类里有三层拦截逻辑:
构造器负责创建 Axios 实例并挂载前两层:
constructor(config: YCRequestConfig) {
this.instance = axios.create(config)
this.showLoading = config.showLoading ?? DEAFULT_LOADING
this.interceptors = config.interceptors
this.instance.interceptors.request.use(
this.interceptors?.requestInterceptor,
this.interceptors?.requestInterceptorCatch
)
this.instance.interceptors.response.use(
this.interceptors?.responseInterceptor,
this.interceptors?.responseInterceptorCatch
)
this.instance.interceptors.request.use(
(config) => {
if (this.showLoading) {
this.loading = ElLoading.service({
lock: true,
text: '正在请求数据。。。',
background: 'rgba(0,0,0,0.5)'
})
}
return config
},
(err) => {
return err
}
)
}
统一响应拦截器里关闭 Loading,并把 res.data 作为业务数据返回:
this.instance.interceptors.response.use(
(res) => {
this.loading?.close()
const data = res.data
if (data.returnCode === '-1001') {
console.log('请求失败~,错误信息')
} else {
return data
}
},
(err) => {
this.loading?.close()
if (err.response.status === 404) {
console.log('404的错误')
}
return err
}
)
这类封装的边界要明确:实例层处理通用行为,业务层处理业务含义。比如登录过期、权限不足、接口错误码,应该按项目规范进一步补齐。
源笔记的 request<T> 用 Promise 包住 Axios 请求,并在请求前后处理单次拦截器和 showLoading:
request<T>(config: YCRequestConfig<T>): Promise<T> {
return new Promise((resolve, reject) => {
if (config.interceptors?.requestInterceptor) {
config = config.interceptors.requestInterceptor(config)
}
if (config.showLoading === false) {
this.showLoading = config.showLoading
}
this.instance
.request<any, T>(config)
.then((res) => {
if (config.interceptors?.responseInterceptor) {
res = config.interceptors.responseInterceptor(res)
}
this.showLoading = DEAFULT_LOADING
resolve(res)
})
.catch((err) => {
this.showLoading = DEAFULT_LOADING
reject(err)
return err
})
})
}
showLoading 在请求结束后重置为默认值,这个细节很重要。否则一次请求关闭 Loading,后续请求可能都不显示。
最后再封装请求方法:
get<T>(config: YCRequestConfig<T>): Promise<T> {
return this.request<T>({ ...config, method: 'GET' })
}
post<T>(config: YCRequestConfig<T>): Promise<T> {
return this.request<T>({ ...config, method: 'POST' })
}
delete<T>(config: YCRequestConfig<T>): Promise<T> {
return this.request<T>({ ...config, method: 'DELETE' })
}
patch<T>(config: YCRequestConfig<T>): Promise<T> {
return this.request<T>({ ...config, method: 'PATCH' })
}
这部分不要过度设计。它的价值只是让调用处更清晰。
源笔记的调用示例:
interface DataType {
data: any
returnCode: string
success: boolean
}
ycRequest
.get<DataType>({
url: '/home/multidata',
showLoading: true,
interceptors: {
requestInterceptor: (config) => {
console.log('单独请求的config')
return config
},
responseInterceptor: (res) => {
console.log('单独响应的res')
return res
}
}
})
.then((res) => {
console.log(res.data)
console.log(res.returnCode)
console.log(res.success)
})
业务代码不用再创建 Axios 实例,也不用重复写 Loading。
这套封装适合中小型 Vue 项目。它的限制也很清楚:
404 和 returnCode,真实项目要补全错误码策略。any 仍然存在,接口返回结构明确后应继续收窄类型。showLoading 对并发请求可能不够精细,多个请求同时进行时需要更严格的 Loading 计数或按请求实例管理。下一步可以把接口按业务模块继续拆分,比如 home.ts、user.ts、order.ts。封装层保持薄,业务接口层负责参数和返回类型,页面组件只调用业务函数。
今日AI领域节奏平缓,DeepSeek V4.1 Flash、MiniMax M3.1 Flash和Mercury 3三款新模型亮相,但短期难以大规模落地。Vercel AI SDK与LangChain.js持续迭代,新增推理参数并完善网关路由。纽约市长呼吁加强AI监管。
OpenAI为GPT-6.2 Astra与Sol强化推理防提取,红队提取成功率从54%降至0.2%,并每周处置数千至数万账号打击协同蒸馏。这提示开发者API行为或更保守,企业需重估蒸馏与微调合规风险,模型能力开放与知识产权保护张力上升。
Codex 好不好用,关键不在提示词,而在工作方式。本文整理 10 条实战技巧:侧边聊与主会话分工、多 Agent 并行、按任务选模型、讨论落成 Spec、按根因批量修 Bug、七成时间做规划、续接旧会话、用 Skill 固化 SOP、多 Agent 交叉审查,以及让 AI 说大白话。
新内容发布后发送确认邮件,不会把未验证或已退订地址加入发送列表。
欢迎理性讨论与补充勘误
无需登录即可评论,展示名称会使用脱敏 IP。
暂无评论