unibest/src/utils/http.ts

77 lines
1.9 KiB
TypeScript
Raw Normal View History

2024-03-27 17:20:05 +08:00
import { CustomRequestOptions } from '@/interceptors/request'
2023-12-23 11:39:46 +08:00
2024-02-01 15:21:36 +08:00
export const http = <T>(options: CustomRequestOptions) => {
2023-12-23 11:39:46 +08:00
// 1. 返回 Promise 对象
2024-02-01 19:51:58 +08:00
return new Promise<IResData<T>>((resolve, reject) => {
2023-12-23 11:39:46 +08:00
uni.request({
...options,
2024-02-01 15:21:36 +08:00
dataType: 'json',
2024-03-07 19:09:34 +08:00
// #ifndef MP-WEIXIN
2024-02-01 15:21:36 +08:00
responseType: 'json',
2024-03-07 19:09:34 +08:00
// #endif
2023-12-23 11:39:46 +08:00
// 响应成功
success(res) {
// 状态码 2xx参考 axios 的设计
if (res.statusCode >= 200 && res.statusCode < 300) {
// 2.1 提取核心数据 res.data
2024-02-01 19:51:58 +08:00
resolve(res.data as IResData<T>)
2023-12-23 11:39:46 +08:00
} else if (res.statusCode === 401) {
// 401错误 -> 清理用户信息,跳转到登录页
2024-01-19 17:28:04 +08:00
// userStore.clearUserInfo()
// uni.navigateTo({ url: '/pages/login/login' })
2023-12-23 11:39:46 +08:00
reject(res)
} else {
// 其他错误 -> 根据后端错误信息轻提示
2024-04-17 15:32:15 +08:00
!options.hideErrorToast &&
uni.showToast({
icon: 'none',
title: (res.data as IResData<T>).msg || '请求错误',
})
2023-12-23 11:39:46 +08:00
reject(res)
}
},
// 响应失败
fail(err) {
uni.showToast({
icon: 'none',
title: '网络错误,换个网络试试',
})
reject(err)
},
})
})
}
2024-05-03 14:53:11 +08:00
/**
* GET
* @param url
* @param query query参数
* @returns
*/
export const httpGet = <T>(url: string, query?: Record<string, any>) => {
return http<T>({
url,
query,
method: 'GET',
})
}
2023-12-23 11:39:46 +08:00
2024-05-03 14:53:11 +08:00
/**
* POST
* @param url
* @param data body参数
* @param query query参数post请求也支持query
* @returns
*/
export const httpPost = <T>(
url: string,
data?: Record<string, any>,
query?: Record<string, any>,
) => {
return http<T>({
url,
query,
data,
method: 'POST',
2024-03-27 17:20:05 +08:00
})
}