【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>
相关推荐
样子20187 小时前
Uniapp 之renderjs解决swiper+多个video卡顿问题
前端·javascript·css·uni-app·html
fakaifa9 小时前
点大餐饮独立版系统源码v1.0.3+uniapp前端+搭建教程
小程序·uni-app·php·源码下载·点大餐饮·扫码点单
Bug改不动了11 小时前
React Native 与 UniApp 对比
react native·react.js·uni-app
anyup14 小时前
🔥🔥 10 天 Star 破百!uView Pro 文档也开源啦:完全免费、无广告、高效上手
前端·vue.js·uni-app
fakaifa1 天前
【最新版】CRMEB Pro版v3.4系统源码全开源+PC端+uniapp前端+搭建教程
人工智能·小程序·uni-app·php·crmeb·源码下载·crmebpro
2501_915918411 天前
iOS 应用上架全流程实践,从开发内测到正式发布的多工具组合方案
android·ios·小程序·https·uni-app·iphone·webview
梦里寻码2 天前
自行食用 uniapp 多端 手写签名组件
前端·uni-app
不如摸鱼去2 天前
Trae 辅助下的 uni-app 跨端小程序工程化开发实践分享
微信小程序·小程序·uni-app·aigc·ai编程
小白_ysf3 天前
uniapp 开发微信小程序,获取经纬度并且转化详细地址(单独封装版本)
微信小程序·uni-app
iOS阿玮3 天前
三年期已满,你的产品不再更新将于90天后下架。
uni-app·app·apple