1、uniapp 拦截器 uni.addInterceptor(STRING,OBJECT)
拦截器中包括基础地址、超时时间、添加请求头标识、添加token
utils文件夹下新建http.ts
拦截uploadFile文件上传,rquest请求接口
cosnt baseUrl = 'xxxx'// 添加拦截器
const httpInterceptor = {//拦截前触发invoke(options:UniApp.RequestOptions) {//非http开头需拼接地址if (!options.url.startWith('http')) { options.url = baseUrl + options.url}// 请求超时,默认60soptions.timeout = 10000//添加小程序端请求头标识,header默认是对象格式options.header = {...options.header,'source-client':'miniapp' }//添加toke请求头标识const token = uni.getStorageSync("token")options.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) => { //返回Peomise对象return new Promise<Data<T>>((resolve, reject) => { uni.request({...options,//请求成功success(res) { if (res.statusCode >= 200 && res.statusCode < 300) {//获取数据成功,调用resolveresolve(res.data as Data<T>)//类型断言为更准确的类型} else if (res.statusCode == 401) {// 401错误,token失效,清除本地存储中的token,跳转到登录页,调用rejectuni.removeStorage({key: 'token',success: function (res) {console.log('成功删除 token');uni.navagateTo({url: '/pages/login/login'})reject(res)},})} else { //通用错误,根据后端错误信息轻提示,调用rejectuni.showToast({icon: 'none',title:(res.data as Data<T>).msg||'请求错误'})reject(res)}},fail(err) {//网络错误,调用rejectuni.showToast({icon: 'none',title:'网络错误'})reject(err) }})})
}
在页面中使用
import {http} from '@/utils/http'<script setup>
import { ref, onMounted} from "vue";
import {http} from '@/utils/http'onMounted(()=>{getData()
})const getData = async ()=>{const res = await http<number[]>({method:'GET',url:'xxx/xxx',header:{}})console.log('获取数据成功',res.result)
}
</script>