Files
2026-10-20 21:19:44 +08:00

90 lines
1.9 KiB
Markdown
Raw Permalink 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 概述
前端使用 Axios 封装 HTTP 请求,自动处理 Token 携带、响应码判断、错误提示。
:::
## 封装结构
```text
src/utils/http/axios/
├── index.ts # Axios 实例配置和拦截器
├── Axios.ts # VAxios 类封装
├── axiosTransform.ts # 数据转换接口
├── checkStatus.ts # HTTP 状态码处理
├── helper.ts # 辅助函数
└── types.ts # 类型定义
```
## 核心拦截器
### 请求拦截器(自动携带 Token)
```typescript
// src/utils/http/axios/index.ts
// 请求前自动添加 Token
config.headers['Authorization'] = `Bearer ${token}`;
```
### 响应拦截器(统一错误处理)
```typescript
// 响应处理逻辑
const { code, data, msg } = res.data;
if (code === 0) {
return data; // 成功,返回 data
}
if (code === 401) {
// Token 过期,跳转登录
router.push('/login');
}
// 其他错误,显示提示
ElMessage.error(msg || '操作失败');
```
:::tip 响应处理规则
- `code === 0`:成功,返回 `data`
- `code === 401`:Token 过期,自动跳转登录页
- `code === 403`:权限不足,显示错误提示
- 其它 `code`:业务失败,显示 `msg`
:::
## API 模块编写
```typescript
// src/api/tool/example.ts
import { http } from '@/utils/http/axios';
export function getExamplePage(params?: Record<string, any>) {
return http.request({
url: '/example/page',
method: 'GET',
params,
});
}
export function exampleAdd(data: any) {
return http.request({
url: '/example/add',
method: 'POST',
data,
});
}
```
## 在组件中使用
```typescript
import { getExamplePage, exampleAdd } from '@/api/tool/example';
// 获取列表
const res = await getExamplePage({ pageNo: 1, pageSize: 10 });
tableData.value = res.records;
// 新增
await exampleAdd({ name: '测试', status: 1 });
```