362 lines
7.0 KiB
Markdown
362 lines
7.0 KiB
Markdown
# 小程序 API 使用指南
|
||
|
||
## 概述
|
||
|
||
小程序使用统一的 API 请求方式,通过 `main.js` 中定义的全局 `apiUrl` 方法进行请求。
|
||
|
||
## 全局 apiUrl 方法
|
||
|
||
### 定义位置
|
||
|
||
`TUICallKit-Vue3/main.js` 中定义了全局的 `apiUrl` 方法:
|
||
|
||
```javascript
|
||
function apiUrl(promise, Loading = true) {
|
||
const token = uni.getStorageSync('token')
|
||
const header = {
|
||
token: token,
|
||
'content-type': 'application/x-www-form-urlencoded',
|
||
...(promise.header || {})
|
||
}
|
||
const data = promise.data || {}
|
||
const url = baseUrl + (promise.url || '')
|
||
|
||
return new Promise((resolve, reject) => {
|
||
if (Loading) {
|
||
uni.showLoading({ title: '加载中...', mask: true })
|
||
}
|
||
|
||
uni.request({
|
||
url: url,
|
||
data: data,
|
||
timeout: 15000,
|
||
method: promise.method || 'POST',
|
||
header: header,
|
||
sslVerify: false,
|
||
success: (res) => {
|
||
const data = res.data
|
||
if (data.code === -1) {
|
||
uni.removeStorageSync('token')
|
||
}
|
||
resolve(data)
|
||
},
|
||
fail: (e) => {
|
||
reject(e)
|
||
},
|
||
complete: (e) => {
|
||
if (Loading) {
|
||
uni.hideLoading()
|
||
}
|
||
}
|
||
})
|
||
})
|
||
}
|
||
```
|
||
|
||
### 参数说明
|
||
|
||
| 参数 | 类型 | 说明 |
|
||
|------|------|------|
|
||
| promise.url | string | 请求URL(相对路径) |
|
||
| promise.method | string | 请求方法(GET/POST,默认POST) |
|
||
| promise.data | object | 请求数据 |
|
||
| promise.header | object | 自定义请求头 |
|
||
| Loading | boolean | 是否显示加载中(默认true) |
|
||
|
||
## API 服务层
|
||
|
||
### 文件位置
|
||
|
||
`TUICallKit-Vue3/utils/api.js`
|
||
|
||
### 基础方法
|
||
|
||
```javascript
|
||
// GET 请求
|
||
export const get = (url, data = {}, loading = false) => {
|
||
return request(url, 'GET', data, loading)
|
||
}
|
||
|
||
// POST 请求
|
||
export const post = (url, data = {}, loading = true) => {
|
||
return request(url, 'POST', data, loading)
|
||
}
|
||
```
|
||
|
||
### 医生 API
|
||
|
||
```javascript
|
||
export const doctorApi = {
|
||
// 获取医生列表
|
||
getDoctorList: (params) => get('/api/doctor/lists', params, false),
|
||
|
||
// 获取医生详情
|
||
getDoctorDetail: (id) => get('/api/doctor/detail', { id }, false),
|
||
|
||
// 获取医生排班
|
||
getDoctorRoster: (doctorId, date) => get('/api/doctor/roster', { doctor_id: doctorId, date }, false)
|
||
}
|
||
```
|
||
|
||
## 使用示例
|
||
|
||
### 1. 在组件中使用
|
||
|
||
```vue
|
||
<script setup>
|
||
import { ref, onMounted } from 'vue'
|
||
import { doctorApi } from '../utils/api'
|
||
|
||
const doctors = ref([])
|
||
const loading = ref(false)
|
||
|
||
// 获取医生列表
|
||
const fetchDoctors = async () => {
|
||
loading.value = true
|
||
try {
|
||
const response = await doctorApi.getDoctorList({
|
||
page_no: 1,
|
||
page_size: 10
|
||
})
|
||
|
||
if (response && response.code === 1) {
|
||
doctors.value = response.data.lists || []
|
||
} else {
|
||
uni.showToast({
|
||
title: response.msg || '获取失败',
|
||
icon: 'none'
|
||
})
|
||
}
|
||
} catch (error) {
|
||
console.error('请求失败:', error)
|
||
uni.showToast({
|
||
title: '网络错误',
|
||
icon: 'none'
|
||
})
|
||
} finally {
|
||
loading.value = false
|
||
}
|
||
}
|
||
|
||
onMounted(() => {
|
||
fetchDoctors()
|
||
})
|
||
</script>
|
||
```
|
||
|
||
### 2. 创建新的 API 模块
|
||
|
||
```javascript
|
||
// utils/api.js 中添加
|
||
|
||
export const appointmentApi = {
|
||
// 获取预约列表
|
||
getAppointmentList: (params) => get('/api/appointment/lists', params, false),
|
||
|
||
// 创建预约
|
||
createAppointment: (data) => post('/api/appointment/create', data, true),
|
||
|
||
// 取消预约
|
||
cancelAppointment: (id) => post('/api/appointment/cancel', { id }, true)
|
||
}
|
||
```
|
||
|
||
### 3. 使用自定义请求头
|
||
|
||
```javascript
|
||
import { request } from '../utils/api'
|
||
|
||
// 发送带自定义请求头的请求
|
||
const response = await request(
|
||
'/api/custom/endpoint',
|
||
'POST',
|
||
{ data: 'value' },
|
||
true,
|
||
{ 'X-Custom-Header': 'custom-value' }
|
||
)
|
||
```
|
||
|
||
## 响应格式
|
||
|
||
### 成功响应
|
||
|
||
```json
|
||
{
|
||
"code": 1,
|
||
"msg": "success",
|
||
"data": {
|
||
"lists": [...],
|
||
"count": 10,
|
||
"page_no": 1,
|
||
"page_size": 10
|
||
}
|
||
}
|
||
```
|
||
|
||
### 失败响应
|
||
|
||
```json
|
||
{
|
||
"code": 0,
|
||
"msg": "错误信息"
|
||
}
|
||
```
|
||
|
||
### 登录失效
|
||
|
||
```json
|
||
{
|
||
"code": -1,
|
||
"msg": "登录已失效"
|
||
}
|
||
```
|
||
|
||
当 `code === -1` 时,会自动清除 token。
|
||
|
||
## 错误处理
|
||
|
||
### 自动处理
|
||
|
||
- 登录失效(code === -1):自动清除 token
|
||
- 网络错误:自动显示加载中/隐藏加载中
|
||
|
||
### 手动处理
|
||
|
||
```javascript
|
||
try {
|
||
const response = await doctorApi.getDoctorList({ page_no: 1 })
|
||
|
||
if (response.code === 1) {
|
||
// 成功处理
|
||
console.log(response.data)
|
||
} else if (response.code === -1) {
|
||
// 登录失效,跳转到登录页
|
||
uni.redirectTo({ url: '/pages/login/login' })
|
||
} else {
|
||
// 其他错误
|
||
uni.showToast({
|
||
title: response.msg || '请求失败',
|
||
icon: 'none'
|
||
})
|
||
}
|
||
} catch (error) {
|
||
// 网络错误
|
||
console.error('网络错误:', error)
|
||
uni.showToast({
|
||
title: '网络错误,请检查连接',
|
||
icon: 'none'
|
||
})
|
||
}
|
||
```
|
||
|
||
## 配置说明
|
||
|
||
### 基础 URL
|
||
|
||
在 `main.js` 中定义:
|
||
|
||
```javascript
|
||
var baseUrl = 'http://api.zzzhengyangtang.cn'
|
||
```
|
||
|
||
修改此值来改变 API 基础地址。
|
||
|
||
### 超时时间
|
||
|
||
在 `main.js` 中的 `uni.request` 中定义:
|
||
|
||
```javascript
|
||
timeout: 15000 // 15秒超时
|
||
```
|
||
|
||
### 请求头
|
||
|
||
默认请求头:
|
||
|
||
```javascript
|
||
{
|
||
token: 'user_token',
|
||
'content-type': 'application/x-www-form-urlencoded'
|
||
}
|
||
```
|
||
|
||
## 常见问题
|
||
|
||
### Q: 如何添加新的 API?
|
||
|
||
A: 在 `utils/api.js` 中添加新的 API 对象:
|
||
|
||
```javascript
|
||
export const newApi = {
|
||
getList: (params) => get('/api/new/lists', params, false),
|
||
create: (data) => post('/api/new/create', data, true)
|
||
}
|
||
```
|
||
|
||
### Q: 如何修改请求头?
|
||
|
||
A: 在 `request` 函数中修改 `header` 对象,或在调用时传入自定义请求头。
|
||
|
||
### Q: 如何处理文件上传?
|
||
|
||
A: 使用 `uni.uploadFile` 而不是 `uni.request`:
|
||
|
||
```javascript
|
||
export const uploadFile = (filePath, url) => {
|
||
return new Promise((resolve, reject) => {
|
||
uni.uploadFile({
|
||
url: baseUrl + url,
|
||
filePath: filePath,
|
||
name: 'file',
|
||
header: {
|
||
token: uni.getStorageSync('token')
|
||
},
|
||
success: (res) => {
|
||
resolve(JSON.parse(res.data))
|
||
},
|
||
fail: (err) => {
|
||
reject(err)
|
||
}
|
||
})
|
||
})
|
||
}
|
||
```
|
||
|
||
### Q: 如何取消请求?
|
||
|
||
A: 小程序的 `uni.request` 不支持直接取消,但可以使用标志位:
|
||
|
||
```javascript
|
||
let requestAborted = false
|
||
|
||
const fetchData = async () => {
|
||
const response = await doctorApi.getDoctorList({ page_no: 1 })
|
||
|
||
if (requestAborted) {
|
||
return
|
||
}
|
||
|
||
// 处理响应
|
||
}
|
||
|
||
// 取消请求
|
||
const abortRequest = () => {
|
||
requestAborted = true
|
||
}
|
||
```
|
||
|
||
## 最佳实践
|
||
|
||
1. **统一 API 管理**:所有 API 调用都通过 `utils/api.js` 进行
|
||
2. **错误处理**:始终使用 try-catch 处理异步请求
|
||
3. **加载状态**:在请求时显示加载中,完成后隐藏
|
||
4. **响应验证**:检查 `code` 字段判断请求是否成功
|
||
5. **token 管理**:自动处理 token 过期情况
|
||
|
||
## 相关文件
|
||
|
||
- API 服务: `TUICallKit-Vue3/utils/api.js`
|
||
- 全局配置: `TUICallKit-Vue3/main.js`
|
||
- 首页示例: `TUICallKit-Vue3/pages/index/index.vue`
|
||
- API 配置: `TUICallKit-Vue3/API_CONFIG.md`
|