当前位置: 首页 > news >正文

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

1、封装http.ts


//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) {// 拦截前触发,拼接urlif (!args.url.startsWith('http')) {args.url = baseUrl + args.url}//请求超时时间,默认60sargs.timeout = 10000//添加小程序请求头标志args.header = {...args.header,'source-client': 'miniapp',}//添加tokenconst token = memberStore.profile?.tokenif (token) {args.header.Authorization = token}},
}
// 添加拦截器
uni.addInterceptor('request', httpInterceptor)
uni.addInterceptor('uploadFile', httpInterceptor)//定义泛型,接口返回的数据结构
interface Data<T> {code: stringmsg: stringresult: 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错误,清理用户信息,跳转登录页,调用rejectmemberStore.clearProfile()uni.navigateTo({ url: '/pages/login/login' })reject(res)} else {//通用错误,调用rejectuni.showToast({title: (res.data as Data<T>).msg || '请求错误',icon: 'none',})reject(res)}},fail(err) {//响应失败,网络错误,调用rejectuni.showToast({title: '网络错误,换个网络试试',icon: 'none',})reject(err)},})})
}

2、封装api


//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


<script setup lang="ts">
import { getBanner } from '@/api/my'const getData = async () => {const res = await getBanner({})console.log(1111, res)
}
</script>
http://www.lryc.cn/news/340293.html

相关文章:

  • 0基础如何入门编程?
  • Go 单元测试基本介绍
  • uniapp 上传视频到阿里云之后回显视频获取视频封面
  • 使用undetected-chromedriver遇到的问题及解决方法,以及它使用SOCKS代理的问题
  • Hadoop入门学习路线
  • Python中的设计模式与最佳实践【第166篇—设计模式】
  • Python赋能AI数据分析开启人工智能新时代
  • TP5使用group报错:1055 Expression #1 of SELECT list is not in GROUP
  • SQL-DML数据操纵语言(Oracle)
  • springboot+axios传参问题
  • (BERT蒸馏)TinyBERT: Distilling BERT for Natural Language Understanding
  • 【数据结构|C语言版】双向链表
  • 适用于 Windows 的 10 个顶级 PDF 编辑器 [免费和付费]
  • 久菜盒子|留学|推荐信|活动类|改性伽马-三氧化二铝催化剂上甲醇制备二甲醚的研究项目
  • Java项目如何使用EasyExcel插件对Excel数据进行导入导出
  • python标准库常用方法集合
  • 智谱AI通用大模型:官方开放API开发基础
  • 单片机家电产品--OC门电路
  • gcc常用命令指南(更新中...)
  • 【深度学习】【机器学习】用神经网络进行入侵检测,NSL-KDD数据集,基于机器学习(深度学习)判断网络入侵,网络攻击,流量异常【3】
  • 两步解决 Flutter Your project requires a newer version of the Kotlin Gradle plugin
  • ArcGIS加载的各类地图怎么去除服务署名水印
  • AttributeError: module ‘cv2.face’ has no attribute ‘LBPHFaceRecognizer_create’
  • 配置路由器实现互通
  • Google Guava第五讲:本地缓存实战及踩坑
  • 一个文生视频MoneyPrinterTurbo项目解析
  • 智能商品计划系统如何提升鞋服零售品牌的竞争力
  • OpenHarmony开发案例:【分布式遥控器】
  • 如何将Oracle 中的部分不兼容对象迁移到 OceanBase
  • Python也可以合并和拆分PDF,批量高效!