interface RequestOptions {
url: string
method?: 'GET' | 'POST' | 'PUT' | 'DELETE'
data?: any
header?: Record<string, string>
}
interface ApiResponse<T = any> {
code: number
message: string
data: T
}
const request = <T = any>(options: RequestOptions): Promise<ApiResponse<T>> => {
return new Promise((resolve, reject) => {
uni.request({
url: import.meta.env.VITE_APP_BASE_API + options.url,
method: options.method || 'GET',
data: options.data || {},
header: options.header || {
'Content-Type': 'application/json',
},
success: (response) => {
const res = response.data as ApiResponse<T>
if (res.code !== 200) {
// 可以在这里处理业务错误
uni.showToast({
title: res.message || '请求出错',
icon: 'none',
})
reject(res)
} else {
resolve(res)
}
},
fail: (error) => {
// 处理网络错误
uni.showToast({
title: '网络请求失败',
icon: 'none',
})
reject(error)
},
})
})
}
export default request
uniapp + vue3 + ts request 封装模版
最新推荐文章于 2024-08-26 15:24:23 发布