## Http请求
轻量级http请求工具,支持 GET、POST、PUT、DELETE、UPLOAD,支持泛型响应和请求缓存。
支持平台
| 安卓 | ios | web | 微信小程序 |
|---|---|---|---|
| √ | √ | √ | √ |
TuiAxios API
构造函数
ts
new TuiAxios({
baseURL: string,
timeout: number,
header: UTSJSONObject
})实例方法
| 方法 | 签名 | 说明 |
|---|---|---|
get | get<T>(path, data?, cache?): Promise<T> | GET 请求 |
post | post<T>(path, data?, cache?): Promise<T> | POST 请求 |
put | put<T>(path, data?, cache?): Promise<T> | PUT 请求 |
delete | delete<T>(path, data?, cache?): Promise<T> | DELETE 请求 |
upload | upload(path, filePath, data?): Promise<UTSJSONObject> | 文件上传 |
abort | abort(): void | 中断请求 |
拦截器
| 属性 | 签名 | 说明 |
|---|---|---|
requestInterceptor | (config: Map<string, any>) => void | 请求拦截,在发送前组装参数 |
responseInterceptor | (res, resolve, reject) => void | 响应拦截,对返回结果统一处理 |
完整示例
创建请求实例(请求和响应拦截处理)
ts
import { TuiStore, TuiAxios } from '@/uni_modules/tui-common'
const store : UTSJSONObject = new TuiStore().value
const reqIns = new TuiAxios({
baseURL: 'https://api.example.com',
timeout: 6000,
header: {
'Content-Type': 'application/json'
}
})
// 请求拦截
reqIns.requestInterceptor = (config : Map<string, any>) => {
const token = store.token ?? ''
const header = config.get('header') as UTSJSONObject
if (token != '') header.set('token', token)
config.set('header', header)
}
// 响应拦截
reqIns.responseInterceptor = (
res : UTSJSONObject,
resolve : (res : UTSJSONObject) => void,
reject : (err : UniError) => void
) => {
const resp : UTSJSONObject = res.data as UTSJSONObject
const code : Number = resp.getNumber('code') as number
if (code == 0) {
resolve(resp)
} else {
const message : string = `${resp.getString('message')}`
reject(new UniError('responseInterceptor', code, message))
}
}
export default reqInsGET 请求
ts
interface UserListResponse {
code: number
data: UserItem[]
message: string
}
export function getUsers(params: { page: number, size: number }): Promise<UserListResponse> {
return reqIns.get<UserListResponse>('/api/users', params)
}
// 页面调用
getUsers({ page: 1, size: 20 }).then((res) => {
console.log(res.data)
}).catch((err) => {
console.error(err)
})POST 请求
ts
interface CreateUserResponse {
code: number
data: { id: number }
message: string
}
export function createUser(data: { name: string, age: number }): Promise<CreateUserResponse> {
return reqIns.post<CreateUserResponse>('/api/user/create', data)
}
// 页面调用
createUser({ name: '张三', age: 25 }).then((res) => {
console.log('创建成功', res.data.id)
})PUT 请求
ts
interface UpdateUserResponse {
code: number
message: string
}
export function updateUser(id: number, data: { name: string, age: number }): Promise<UpdateUserResponse> {
return reqIns.put<UpdateUserResponse>(`/api/user/${id}`, data)
}
// 页面调用
updateUser(1, { name: '李四', age: 30 }).then((res) => {
console.log('更新成功')
})DELETE 请求
ts
interface DeleteUserResponse {
code: number
message: string
}
export function deleteUser(id: number): Promise<DeleteUserResponse> {
return reqIns.delete<DeleteUserResponse>('/api/user/delete', { id })
}
// 页面调用
deleteUser(1).then((res) => {
console.log('删除成功')
})请求缓存
所有请求方法(get/post/put/delete)支持第三个参数 cache,开启后以 URL+参数 的 MD5 为 key 缓存响应结果:
ts
// 开启缓存,第二次相同请求直接返回缓存结果
reqIns.get('/api/data', { key: 'value' }, true)
reqIns.post('/api/data', { key: 'value' }, true)文件上传
ts
interface UploadResponse {
code: number
data: { url: string }
message: string
}
export function uploadAvatar(filePath: string): Promise<UploadResponse> {
return reqIns.upload('/api/upload/avatar', filePath, {
type: 'avatar'
}) as Promise<UploadResponse>
}
// 页面调用
uni.chooseImage({
count: 1,
success: (res) => {
uploadAvatar(res.tempFilePaths[0]).then((res) => {
console.log('上传成功', res.data.url)
})
}
})中断请求
abort() 中断当前实例正在进行的请求,适用于搜索防重发、页面卸载取消等场景。
ts
// 搜索场景:每次搜索前中断上一次未完成的请求
function onSearch(keyword: string) {
reqIns.abort()
reqIns.get('/api/search', { keyword }).then((res) => {
list.value = res.data
})
}
// 页面卸载时中断
onBeforeUnmount(() => {
reqIns.abort()
})如果需要同时管理多个请求,可以为不同场景创建独立的 TuiAxios 实例:
ts
const searchAxios = new TuiAxios({ baseURL: 'https://api.example.com', timeout: 6000 })
const uploadAxios = new TuiAxios({ baseURL: 'https://upload.example.com', timeout: 30000 })
function onSearch(keyword: string) {
searchAxios.abort() // 只中断搜索请求
searchAxios.get('/api/search', { keyword }).then((res) => {
list.value = res.data
})
}
function uploadFile(path: string) {
uploadAxios.upload('/api/upload', path, { type: 'avatar' })
}
onBeforeUnmount(() => {
searchAxios.abort()
uploadAxios.abort()
})