# 10. HTTP 请求
URL: /%E6%96%87%E6%A1%A3/04.%E5%BC%80%E5%8F%91%E6%96%87%E6%A1%A3/01.%20%E5%89%8D%E7%AB%AF%E5%BC%80%E5%8F%91/02.%20%E6%A0%B8%E5%BF%83%E6%8A%80%E6%9C%AF/12.%20HTTP%20%E8%AF%B7%E6%B1%82

HTTP 请求封装使用指南


# HTTP 请求封装

> [!info] 项目使用 Axios 1.7.9 进行 HTTP 请求封装。

## defHttp 使用

项目封装了 `defHttp` 请求工具：

```typescript
import { defHttp } from '@/utils/http/axios';

// GET 请求
defHttp.get({
  url: '/api/list',
  params: { page: 1, pageSize: 20 },
});

// POST 请求
defHttp.post({
  url: '/api/create',
  data: { name: 'test' },
});

// 通用请求
defHttp.request({
  url: '/api/detail',
  method: 'GET',
  params: { id },
});
```

## API 定义

### 定义 API 路径

```typescript
// src/api/sys/user.ts
import { defHttp } from '@/utils/http/axios';

enum Api {
  GetList = '/system/user/list',
  GetDetail = '/system/user/detail',
  Create = '/system/user/create',
  Update = '/system/user/update',
  Delete = '/system/user/delete',
}

// 列表
export function getUserList(params: PageParams) {
  return defHttp.get<UserListResult>({
    url: Api.GetList,
    params,
  });
}

// 详情
export function getUserDetail(id: string) {
  return defHttp.get<UserDetailResult>({
    url: Api.GetDetail,
    params: { id },
  });
}

// 创建
export function createUser(data: CreateUserParams) {
  return defHttp.post({
    url: Api.Create,
    data,
  });
}

// 更新
export function updateUser(id: string, data: UpdateUserParams) {
  return defHttp.put({
    url: Api.Update,
    data: { id, ...data },
  });
}

// 删除
export function deleteUser(id: string) {
  return defHttp.delete({
    url: Api.Delete,
    data: { id },
  });
}
```

### 类型定义

```typescript
// src/api/sys/user/model.ts

export interface UserItem {
  id: string;
  username: string;
  realname: string;
  email?: string;
  phone?: string;
  status: number;
  createTime: string;
}

export interface UserListResult {
  records: UserItem[];
  total: number;
  current: number;
  size: number;
}

export interface PageParams {
  current: number;
  size: number;
  keyword?: string;
}

export interface CreateUserParams {
  username: string;
  realname: string;
  password: string;
  email?: string;
  phone?: string;
}

export interface UpdateUserParams {
  realname?: string;
  email?: string;
  phone?: string;
  status?: number;
}
```

## 请求配置

### 超时配置

```typescript
defHttp.request({
  url: '/api/upload',
  timeout: 60000, // 60秒超时
});
```

### 错误处理

```typescript
defHttp.request({
  url: '/api/detail',
  errorMessageMode: 'message', // 使用 message 提示错误
  // errorMessageMode: 'modal', // 使用 modal 提示错误
});
```

### 返回原生响应

```typescript
defHttp.request({
  url: '/api/export',
  isReturnNativeResponse: true, // 返回原生 Axios 响应
});
```

## 响应处理

### 默认响应格式

```typescript
{
  "code": 200,
  "result": { /* 实际数据 */ },
  "message": "success",
  "success": true
}
```

### 请求拦截器

```typescript
// src/utils/http/axios/index.ts

requestInterceptors: (config, options) => {
  // 1. 添加 token
  const token = getToken();
  if (token) {
    config.headers.Authorization = options.authenticationScheme
      ? `${options.authenticationScheme} ${token}`
      : 'Bearer ' + token;
    config.headers[ConfigEnum.TOKEN] = token;
  }

  // 2. 添加租户 ID
  let tenantId = getTenantId();
  if (!tenantId) {
    tenantId = 0;
  }
  config.headers[ConfigEnum.TENANT_ID] = tenantId;

  // 3. 添加签名和时间戳
  config.headers[ConfigEnum.TIMESTAMP] = signMd5Utils.getTimestamp();
  config.headers[ConfigEnum.SIGN] = signMd5Utils.getSign(
    config.url,
    cloneDeep(config.params),
    cloneDeep(config.data)
  );

  // 4. 添加版本标记
  config.headers[ConfigEnum.VERSION] = 'v3';

  // 5. 多数据源头（Mini/Offi/CP 模块）
  if (isMni === 'true' || isOffi === 'true' || isCp === 'true') {
    config.headers[ConfigEnum.MINI_ALIAS] = miniAlias;
    config.headers[ConfigEnum.OFFI_ALIAS] = offiAlias;
    config.headers[ConfigEnum.CP_ALIAS] = cpAlias;
  }

  return config;
},
```

### 响应拦截器

```typescript
responseInterceptors: (res: AxiosResponse<any>) => {
  return res;
},

responseInterceptorsCatch: (error: any) => {
  const { response, code, message } = error || {};

  // 处理超时
  if (code === 'ECONNABORTED' && message?.includes('timeout')) {
    showError('请求超时');
  }

  // 网络错误
  if (code?.includes('Network Error')) {
    showError('网络异常');
  }

  // HTTP 状态码错误
  checkStatus(error?.response?.status, message);

  return Promise.reject(error);
},
```

## 文件上传

```typescript
export function uploadFile(file: File) {
  const formData = new FormData();
  formData.append('file', file);

  return defHttp.upload<{
    url: string;
    filename: string;
  }>({
    url: '/api/file/upload',
    data: formData,
  });
}
```

## 文件下载

```typescript
export function downloadFile(id: string) {
  return defHttp.request({
    url: '/api/file/download',
    method: 'GET',
    params: { id },
    responseType: 'blob', // 二进制响应
  });
}

// 使用示例
import { downloadFile } from '@/api/file';

async function handleDownload(id: string) {
  const blob = await downloadFile(id);
  const url = window.URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = 'filename.xlsx';
  a.click();
  window.URL.revokeObjectURL(url);
}
```

## 请求头字段

项目使用的自定义请求头：

| 字段 | 说明 |
|------|------|
| `X-Access-Token` | JWT 访问令牌 |
| `X-Tenant-Id` | 租户 ID |
| `X-TIMESTAMP` | 请求时间戳（用于签名） |
| `X-Sign` | 请求签名 |
| `X-V3-VERSION` | 版本标记（固定为 v3） |
| `X-MINI-Alias` | 小程序数据源别名 |
| `X-OFFI-Alias` | 公众号数据源别名 |
| `X-CP-Alias` | 企业微信数据源别名 |
| `X-LOW-APP-ID` | 低代码应用 ID |

## 多数据源切换

项目支持多个数据源，通过请求头切换：

```typescript
// 小程序模块
if (config.url && config.url.includes(DataSourcePath.MINI)) {
  const miniAlias = ls.get(MINI_DATA_SOURCE)?.datasourceAlias;
  config.headers[ConfigEnum.MINI_ALIAS] = miniAlias;
}

// 公众号模块
if (config.url && config.url.includes(DataSourcePath.OFFI)) {
  const offiAlias = ls.get(OFFI_DATA_SOURCE)?.datasourceAlias;
  config.headers[ConfigEnum.OFFI_ALIAS] = offiAlias;
}

// 企业微信模块
if (config.url && config.url.includes(DataSourcePath.CP)) {
  const cpAlias = ls.get(CP_DATA_SOURCE)?.datasourceAlias;
  config.headers[ConfigEnum.CP_ALIAS] = cpAlias;
}
```

## 错误码定义

```typescript
// src/enums/httpEnum.ts

export enum ResultEnum {
  SUCCESS = 0,
  ERROR = -1,
  TIMEOUT = 401,
  NOT_FOUND = 404,
  FORBIDDEN = 403,
  SERVER_ERROR = 500,
}
```

## 取消请求

```typescript
import { AxiosCanceler } from '@/utils/http/axios/axiosCancel';

// 取消所有请求
const axiosCanceler = new AxiosCanceler();
axiosCanceler.removeAllPending();

// 取消特定请求
axiosCanceler.removePendingRequest({
  url: '/api/list',
});
```

## 相关文件

```
src/utils/http/axios/
├── Axios.ts              # Axios 实例
├── axiosCancel.ts        # 取消重复请求
├── axiosTransform.ts     # 数据转换
├── checkStatus.ts        # 状态码检查
└── index.ts              # 请求封装导出
```
