87 lines
2.1 KiB
TypeScript
87 lines
2.1 KiB
TypeScript
import { CustomRequestOptions } from '@/interceptors/request'
|
||
import { useUserStore } from '@/store'
|
||
|
||
export const http = <T>(options: CustomRequestOptions) => {
|
||
return new Promise<IResData<T>>((resolve, reject) => {
|
||
const timestamp = new Date().getTime()
|
||
|
||
uni.request({
|
||
...options,
|
||
dataType: 'json',
|
||
// #ifndef MP-WEIXIN
|
||
responseType: 'json',
|
||
// #endif
|
||
// 响应成功
|
||
success(res) {
|
||
if (res.statusCode >= 200 && res.statusCode < 300) {
|
||
if (res.data.errorCode === 403) {
|
||
const $user = useUserStore()
|
||
$user.logout()
|
||
uni.switchTab({
|
||
url: '/pages/home/home'
|
||
})
|
||
uni.showToast({
|
||
icon: 'none',
|
||
title: '登录已过期,请重新登录'
|
||
})
|
||
reject(res)
|
||
} else {
|
||
resolve(res.data as IResData<T>)
|
||
}
|
||
} else {
|
||
uni.showToast({
|
||
icon: 'none',
|
||
title: '网络错误,请重试'
|
||
})
|
||
reject(res)
|
||
}
|
||
},
|
||
// 响应失败
|
||
fail(err) {
|
||
console.log('请求失败', err)
|
||
uni.showToast({
|
||
icon: 'none',
|
||
title: '网络错误,请重试'
|
||
})
|
||
reject(err)
|
||
},
|
||
complete(res) {
|
||
console.log(options.url, {
|
||
env: import.meta.env.VITE_APP_ENV,
|
||
statusCode: res?.statusCode,
|
||
code: res?.data?.errorCode,
|
||
baseUrl: import.meta.env.VITE_SERVER_BASEURL,
|
||
url: options.url,
|
||
req: options.data,
|
||
res: res?.data?.data,
|
||
header: options.header,
|
||
message: res?.data?.errorMsg,
|
||
duration: new Date().getTime() - timestamp
|
||
})
|
||
}
|
||
})
|
||
})
|
||
}
|
||
|
||
/**
|
||
* 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'
|
||
})
|
||
}
|
||
|
||
http.post = httpPost
|