7.0 KiB
7.0 KiB
小程序 API 使用指南
概述
小程序使用统一的 API 请求方式,通过 main.js 中定义的全局 apiUrl 方法进行请求。
全局 apiUrl 方法
定义位置
TUICallKit-Vue3/main.js 中定义了全局的 apiUrl 方法:
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
基础方法
// 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
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. 在组件中使用
<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 模块
// 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. 使用自定义请求头
import { request } from '../utils/api'
// 发送带自定义请求头的请求
const response = await request(
'/api/custom/endpoint',
'POST',
{ data: 'value' },
true,
{ 'X-Custom-Header': 'custom-value' }
)
响应格式
成功响应
{
"code": 1,
"msg": "success",
"data": {
"lists": [...],
"count": 10,
"page_no": 1,
"page_size": 10
}
}
失败响应
{
"code": 0,
"msg": "错误信息"
}
登录失效
{
"code": -1,
"msg": "登录已失效"
}
当 code === -1 时,会自动清除 token。
错误处理
自动处理
- 登录失效(code === -1):自动清除 token
- 网络错误:自动显示加载中/隐藏加载中
手动处理
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 中定义:
var baseUrl = 'http://api.zzzhengyangtang.cn'
修改此值来改变 API 基础地址。
超时时间
在 main.js 中的 uni.request 中定义:
timeout: 15000 // 15秒超时
请求头
默认请求头:
{
token: 'user_token',
'content-type': 'application/x-www-form-urlencoded'
}
常见问题
Q: 如何添加新的 API?
A: 在 utils/api.js 中添加新的 API 对象:
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:
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 不支持直接取消,但可以使用标志位:
let requestAborted = false
const fetchData = async () => {
const response = await doctorApi.getDoctorList({ page_no: 1 })
if (requestAborted) {
return
}
// 处理响应
}
// 取消请求
const abortRequest = () => {
requestAborted = true
}
最佳实践
- 统一 API 管理:所有 API 调用都通过
utils/api.js进行 - 错误处理:始终使用 try-catch 处理异步请求
- 加载状态:在请求时显示加载中,完成后隐藏
- 响应验证:检查
code字段判断请求是否成功 - token 管理:自动处理 token 过期情况
相关文件
- API 服务:
TUICallKit-Vue3/utils/api.js - 全局配置:
TUICallKit-Vue3/main.js - 首页示例:
TUICallKit-Vue3/pages/index/index.vue - API 配置:
TUICallKit-Vue3/API_CONFIG.md