# 前端 API 层 前端 API 层负责封装后端接口的 HTTP 请求。每个业务模块对应一个 API 文件,使用项目封装的 Axios 工具发送请求。 ## 文件位置 ``` ui/src/api/tool/example.ts ``` ## 完整代码 ```typescript import { http } from '@/utils/http/axios'; /** * @description: 案例分页列表 */ export function getExamplePage(params?) { return http.request({ url: '/example/page', method: 'GET', params, }); } /** * 获取全部案例列表 * @param params 参数 * @returns 返回结果 */ export function getExampleList(params?) { return http.request({ url: '/example/list', method: 'GET', params, }); } /** * @description: 根据ID获取案例详情 * @param id 案例ID */ export function getExampleDetail(id) { return http.request({ url: '/example/detail/' + id, method: 'get', }); } /** * @description: 添加案例 * @param data 案例数据 */ export function exampleAdd(data: any) { return http.request({ url: '/example/add', method: 'POST', data, }); } /** * @description: 更新案例 * @param data 案例数据 */ export function exampleUpdate(data: any) { return http.request({ url: '/example/update', method: 'PUT', data, }); } /** * @description: 删除案例 * @param id 案例ID */ export function exampleDelete(id) { return http.request({ url: '/example/delete/' + id, method: 'DELETE', }); } /** * @description: 批量删除案例 * @param data 案例ID数组 */ export function exampleBatchDelete(data: any) { return http.request({ url: '/example/batchDelete', method: 'DELETE', data, }); } ``` ## 代码解析 ### HTTP 客户端 ```typescript import { http } from '@/utils/http/axios'; ``` `http` 是项目封装的 Axios 实例,自动处理: - **请求拦截**:添加 JWT Token(`Authorization: Bearer xxx`) - **响应拦截**:统一处理错误码、弹出提示 - **基础路径**:自动拼接 `/api` 前缀(通过 Vite 代理转发到后端) ### 请求方式 ```typescript http.request({ url: '/example/page', // 接口路径(不含 /api 前缀) method: 'GET', // HTTP 方法 params, // GET 参数(拼接到 URL 查询字符串) }) ``` | 参数 | 用途 | |:----|:----| | `url` | 接口路径,与后端 urls.py 定义的 path 对应 | | `method` | HTTP 方法:GET / POST / PUT / DELETE | | `params` | GET 请求参数(拼接到 URL) | | `data` | POST/PUT/DELETE 请求体(JSON) | ### 函数命名规范 | 模式 | 示例 | 说明 | |:----|:----|:----| | `get{Module}Page` | `getExamplePage` | 分页列表查询 | | `get{Module}List` | `getExampleList` | 全量列表查询 | | `get{Module}Detail` | `getExampleDetail` | 详情查询 | | `{module}Add` | `exampleAdd` | 新增 | | `{module}Update` | `exampleUpdate` | 更新 | | `{module}Delete` | `exampleDelete` | 单条删除 | | `{module}BatchDelete` | `exampleBatchDelete` | 批量删除 | ### 参数传递区别 ```typescript // GET:参数通过 params 传递(拼接到 URL 查询字符串) http.request({ url: '/example/page', method: 'GET', params }) // POST/PUT/DELETE:参数通过 data 传递(放入请求体 JSON) http.request({ url: '/example/add', method: 'POST', data }) // 路径参数:直接拼接到 URL http.request({ url: '/example/delete/' + id, method: 'DELETE' }) ``` ## 页面中的调用方式 ```vue ``` ## 开发要点 1. **一个模块一个文件**:放在 `ui/src/api/{group}/` 目录下 2. **URL 不含 `/api` 前缀**:Vite 代理自动拼接 3. **GET 用 `params`,POST/PUT/DELETE 用 `data`**:参数传递方式不同 4. **路径参数直接拼接到 URL**:如 `/example/delete/` + id 5. **批量删除的参数是数组**:`data: [1, 2, 3]` ## 总结 前端 API 层使用封装后的 Axios 发送请求,URL 使用相对路径(不含 `/api` 前缀),函数命名采用 `get{Module}Page` / `{module}Add` 格式。GET 请求用 `params`,POST/PUT/DELETE 用 `data`,响应拦截器自动处理错误。