Files
easygoadmin-wiki/EasyGoAdmin_Gin_NaiveVue/zh/frontend/http.md
T
2026-10-25 17:24:27 +08:00

68 lines
2.0 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 9.4 HTTP 请求封装
:::tip 概述
`utils/http/axios` 是自研的 axios 封装层:请求拦截(前缀、Token)、响应拦截(信封解包、错误提示、401 处理)、取消重复请求。业务代码只面对"成功拿 data"的干净接口。
:::
## 文件结构
```text
utils/http/axios/
├── Axios.ts axios 实例创建与拦截器装配
├── axiosTransform.ts 转换器基类(各拦截点的抽象)
├── index.ts 本项目转换器实现(核心业务逻辑)
├── checkStatus.ts HTTP 状态码 → 提示文案映射
├── axiosCancel.ts 重复请求取消
├── helper.ts 辅助函数
└── types.ts 类型定义
```
## 拦截流程
```text
请求发出
→ 前置:拼接 VITE_GLOB_API_URL_PREFIX + URL,附加 Authorization: Bearer
→ 发送(重复请求按策略取消)
↓
响应返回
→ 后置:判断 HTTP 状态 → 解包信封
ok=true → 返回 data(业务函数直接拿数据)
code=401 → 清令牌跳登录(或触发刷新)
其余失败 → 统一 toast msg,抛错给调用方 catch
↓
业务代码
```
## 使用形态(摘自 ui/src/api/tool/example.ts)
```typescript
import { http } from '@/utils/http/axios';
export function getExamplePage(params?: Record<string, any>) {
return http.request({
url: '/example/page',
method: 'GET',
params,
});
}
```
注意 URL **不带 /api 前缀**(由配置统一拼接);Token 与信封判断都不在业务层出现。
## 错误处理约定
| 层 | 行为 |
|---|---|
| 拦截器 | 统一 toast + 401 跳转;返回 reject |
| api 模块 | 不 catch(透传) |
| 页面 | 需要特殊处理才 catch(如表单保留输入),否则由拦截器兜底提示 |
## 类型支持
`http.request<T>()` 支持泛型标注返回 data 类型,逐步为 api 模块补类型是推荐实践。
## 相关
- [8.1 统一响应格式](/zh/api-spec/response.html)(信封契约)
- [9.14 API 模块编写规范](/zh/frontend/api-module.html)