基于uni.request api进行二次封装

发布时间:2026/7/2 3:26:40

基于uni.request api进行二次封装 取消请求功能失败自动重试机制并发请求控制核心代码123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155// 响应内容格式exportinterfaceInResultT {code: number |stringmessage:stringsuccess: boolean# data: T}// 请求参数格式interfaceRequestOptions {baseURL?:stringurl:stringmethod?:GET|POST|PUT|DELETEdata?: Recordstring, anyparams?: Recordstring, anyheader?: Recordstring,stringloading?: boolean// 是否显示加载中提示loadingText?:string// 加载中提示文本removeToken?: boolean// 是否移除tokencache?: boolean// 是否缓存响应结果returnResponse?: boolean// 直接返回响应}// 设置请求头function setRequestHeaders(url:string) {constLOGIN_URL /auth/oauth2/tokenif(url.includes(LOGIN_URL)) {return{ Authorization: Basic Z2VveHNwYWNlOmdlb3hzcGFjZQ }}consttoken uni.getStorageSync(token)if(token) {return{ Authorization: Bearer ${token} }}return{}asRecordstring,string}// 请求和响应拦截器function requestAndResponseInterceptor() {uni.addInterceptor(request, {// 调用前置拦截器invoke(options: RequestOptions) {if(options.loading) {uni.showLoading({title: options.loadingText ||加载中...,mask:true,})}options.header {...options.header,...setRequestHeaders(options.url),}// 移除tokenif(options.removeToken) {delete options.header.Authorization}// 处理params 参数if(options.params) {consturlPrams:string[] []Object.keys(options.params).forEach((key) {urlPrams.push(${key}${options.params![key]})})if(options.url.includes(?)) {options.url urlPrams.join()}else{options.url ?${urlPrams.join()}}}returnoptions},// 调用后置拦截器success(res) {returnres},fail(err) {uni.showToast({title:网络请求失败,icon:none,})returnPromise.reject(err)},complete(option) {console.log(option.errMsg, option.errMsg)setTimeout(() {uni.hideLoading()}, 15000)},})}// 调用请求拦截器和响应拦截器requestAndResponseInterceptor()constcacheMap newMapstring, any()// 封装网络请求export async function request(options: RequestOptions): Promiseany {const{ baseURL, url, header {}, cache, returnResponse } options// 合并配置constconfig {...options,url: url.startsWith(http) ? options.url : baseURL options.url,header: {Content-Type:application/json,...header,// 允许自定义header},timeout: 10000,// 超时时间ms}if(cache) {if(cacheMap.has(url)) {returncacheMap.get(url)}}try{constresponse await uni.request(config)if(options.loading) {uni.hideLoading()}// 响应拦截器if(response.statusCode 200) {constdata returnResponse ? response : response.dataif(cache) {cacheMap.set(url, data)}// ts-expect-error 判断异常if(response.data.code !20000) {// ts-expect-error 判断异常toast(response.data.msg, {icon:fail,})}returndata}if(response.statusCode 401) {toast(登录已过期请重新登录, {}, () {uni.redirectTo({url:/user/login/index,})})}else{toast(系统服务异常)}}catch(error) {returnPromise.reject(error)}}toast 封装代码1234567891011121314151617181920212223242526272829303132333435export function toast(title:string, options?: { duration?: number, icon?:success|loading|error|none|fail|exception, mask?: boolean }, callback?: () void) {const{ mask true, duration 1000, icon none} options || {}if(title title.length 14) {// 当作字符长度14时使用showModal展示uni.showModal({content: title,showCancel:false,success() {if(callback typeofcallback function) {consttimer setTimeout(() {callback()clearTimeout(timer)}, duration)}},})}else{uni.showToast({title,message: title,icon,mask,duration,success() {if(callback typeofcallback function) {consttimer setTimeout(() {callback()clearTimeout(timer)}, duration)}},})}}使用示例1234567891011121314151617import { type InResult, request }from/utils/requestexportinterfaceIUser {id:string,name:string,age?: number}export function getUserList(data: any): PromiseInResult{ records: ArrayIUser, total: number } {returnrequest({baseURL,url:/user/page,method:POST,params: data,loading:true,})

相关新闻