1、封装http.ts
import { useMemberStore } from '@/stores/index'
const memberStore = useMemberStore()
const baseUrl = 'https://xx/xx/xx'
const httpInterceptor = {
invoke(args: UniApp.RequestOptions) {
if (!args.url.startsWith('http')) {
args.url = baseUrl + args.url
}
args.timeout = 10000
args.header = {
...args.header,
'source-client': 'miniapp',
}
const token = memberStore.profile?.token
if (token) {
args.header.Authorization = token
}
},
}
uni.addInterceptor('request', httpInterceptor)
uni.addInterceptor('uploadFile', httpInterceptor)
interface Data<T> {
code: string
msg: string
result: T
}
export const http = <T>(options: UniApp.RequestOptions) => {
return new Promise<Data<T>>((resolve, reject) => {
uni.request({
...options,
success(res) {
if (res.statusCode >= 200 && res.statusCode < 300) {
resolve(res.data as Data<T>)
} else if (res.statusCode === 401) {
memberStore.clearProfile()
uni.navigateTo({ url: '/pages/login/login' })
reject(res)
} else {
uni.showToast({
title: (res.data as Data<T>).msg || '请求错误',
icon: 'none',
})
reject(res)
}
},
fail(err) {
uni.showToast({
title: '网络错误,换个网络试试',
icon: 'none',
})
reject(err)
},
})
})
}
2、封装api
import { http } from '@/utils/http'
export const getBanner = (data: any) => {
return http<string[]>({
url: '/xx/xx',
method: 'GET',
data: data,
})
}
3、使用封装好的api
<script setup lang="ts">
import { getBanner } from '@/api/my'
const getData = async () => {
const res = await getBanner({})
console.log(1111, res)
}
</script>