【uniapp】request请求函数封装,token、成功、失败等

1、封装http.ts

javascript 复制代码
//utils--->http.ts

/**
 * 添加拦截器
 *  拦截request请求
 *  拦截uploadFile文件上传
 *
 * TODO
 *  1、非http开头需要拼接地址
 *  2、请求超时
 *  3、添加小程序端请求头标识
 *  4、添加token请求头标识
 */
import { useMemberStore } from '@/stores/index'
const memberStore = useMemberStore()

//实际项目种的baseUrl是根据环境变量来获取的
const baseUrl = 'https://xx/xx/xx'

const httpInterceptor = {
  invoke(args: UniApp.RequestOptions) {
    // 拦截前触发,拼接url
    if (!args.url.startsWith('http')) {
      args.url = baseUrl + args.url
    }

    //请求超时时间,默认60s
    args.timeout = 10000

    //添加小程序请求头标志
    args.header = {
      ...args.header,
      'source-client': 'miniapp',
    }

    //添加token
    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) {
          //401错误,清理用户信息,跳转登录页,调用reject
          memberStore.clearProfile()
          uni.navigateTo({ url: '/pages/login/login' })
          reject(res)
        } else {
          //通用错误,调用reject
          uni.showToast({
            title: (res.data as Data<T>).msg || '请求错误',
            icon: 'none',
          })
          reject(res)
        }
      },
      fail(err) {
        //响应失败,网络错误,调用reject
        uni.showToast({
          title: '网络错误,换个网络试试',
          icon: 'none',
        })
        reject(err)
      },
    })
  })
}

2、封装api

javascript 复制代码
//api--->my.ts
import { http } from '@/utils/http'

export const getBanner = (data: any) => {
  return http<string[]>({
    url: '/xx/xx',
    method: 'GET',
    data: data,
  })
}

3、使用封装好的api

javascript 复制代码
<script setup lang="ts">
import { getBanner } from '@/api/my'

const getData = async () => {
  const res = await getBanner({})
  console.log(1111, res)
}
</script>
相关推荐
BumBle11 分钟前
基于UniApp实现DeepSeek AI对话:流式数据传输与实时交互技术解析
前端·uni-app
会点法律的程序员1 小时前
小程序 地理位置授权怎么搞
前端·小程序·uni-app
重生之我是菜鸡程序员1 小时前
uniapp 顶部通知 上滑隐藏
前端·javascript·uni-app
FliPPeDround1 小时前
告别 uni-app 启动烦恼:@uni-helper/unh 让开发流程更顺畅
前端·微信小程序·uni-app
2501_915921434 小时前
iOS 26 电耗监测与优化,耗电问题实战 + 多工具 辅助策略
android·macos·ios·小程序·uni-app·cocoa·iphone
2501_915921434 小时前
苹果软件混淆与 iOS 应用加固白皮书,IPA 文件加密、反编译防护与无源码混淆方案全解析
android·ios·小程序·https·uni-app·iphone·webview
anyup5 小时前
🔥开源零配置!10 分钟上手:create-uni + uView Pro 快速搭建企业级 uni-app 项目
前端·前端框架·uni-app
你真的可爱呀5 小时前
uniapp学习【vue3在uniapp中语法,使用element,使用uView UI】
学习·uni-app
保利威直播5 小时前
保利威uniapp直播插件功能清单-开播端/主播端/观看端(持续测试更新中...)
uni-app·直播·直播平台
dcloud_jibinbin6 小时前
【uniapp】体验优化:开源工具集 uni-toolkit 发布
前端·webpack·性能优化·小程序·uni-app·vue