81 lines
1.9 KiB
TypeScript
Raw Normal View History

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