【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>
相关推荐
2501_915921431 小时前
掌握 iOS 26 App 性能监控,从监测到优化的多工具组合流程
android·macos·ios·小程序·uni-app·cocoa·iphone
勉灬之1 小时前
通过npm run XXX命令生成uniapp的pages.json文件
npm·uni-app·json
知识分享小能手2 小时前
uni-app 入门学习教程,从入门到精通, uni-app常用API的详细语法知识点(上)(5)
前端·javascript·vue.js·学习·微信小程序·小程序·uni-app
2501_916008893 小时前
手机 iOS 系统全解析,生态优势、开发机制与跨平台应用上架实践指南
android·ios·智能手机·小程序·uni-app·iphone·webview
00后程序员张5 小时前
Fiddler使用教程,全面掌握Fiddler抓包工具的配置方法、代理设置与调试技巧(HTTPHTTPS全解析)
前端·测试工具·ios·小程序·fiddler·uni-app·webview
2501_916008895 小时前
HTTPS 下的 DDoS 防护与抓包分析实战,从检测到快速缓解的工程化打法
网络协议·ios·小程序·https·uni-app·iphone·ddos
2501_915918415 小时前
App 使用 HTTPS 的工程化实战,从接入到真机排查的一线指南
android·ios·小程序·https·uni-app·iphone·webview
Rysxt_5 小时前
Electron 与 uni-app 区别教程:如何选择适合你的跨平台开发框架?
javascript·electron·uni-app·跨平台
2501_9159090618 小时前
“绑定 HTTPS” 的工程全流程 从证书配置到真机验证与故障排查
网络协议·http·ios·小程序·https·uni-app·iphone
2501_9159184119 小时前
iOS 混淆实战 多工具组合完成 IPA 混淆、加固与工程化落地(iOS混淆|IPA加固|无源码混淆|Ipa Guard|Swift Shield)
android·ios·小程序·https·uni-app·iphone·webview