小程序学习(十三)之请求和上传文件拦截器

拦截器文档:点击跳转

接口文档:点击跳转

复制代码
//http.ts
import { useMemberStore } from '@/stores'


// 请求基地址
const baseURL = 'https://pcapi-xiaotuxian-front-devtest.itheima.net'

// 拦截器配置
const httpInterceptor = {
  // 拦截前触发
  invoke(options: UniApp.RequestOptions) {
    // 1. 非 http 开头需拼接地址
    if (!options.url.startsWith('http')) {
      options.url = baseURL + options.url
    }
    // 2. 请求超时
    options.timeout = 10000
    
    // 3. 添加小程序端请求头标识
    options.header = {
      'source-client': 'miniapp',
      ...options.header,
    }
    // 4. 添加 token 请求头标识
    const memberStore = useMemberStore()
    const token = memberStore.profile?.token
    if (token) {
      options.header.Authorization = token
    }
    console.log(options)
  },
}

// 拦截 request 请求
uni.addInterceptor('request', httpInterceptor)
// 拦截 uploadFile 文件上传
uni.addInterceptor('uploadFile', httpInterceptor)

/**
 * 请求函数
 * @param  UniApp.RequestOptions
 * @returns Promise
 *  1. 返回 Promise 对象,用于处理返回值类型
 *  2. 获取数据成功
 *    2.1 提取核心数据 res.data
 *    2.2 添加类型,支持泛型
 *  3. 获取数据失败
 *    3.1 401错误  -> 清理用户信息,跳转到登录页
 *    3.2 其他错误 -> 根据后端错误信息轻提示
 *    3.3 网络错误 -> 提示用户换网络
 */
type Data<T> = {
  code: string
  msg: string
  result: T
}
// 2.2 添加类型,支持泛型
export const http = <T>(options: UniApp.RequestOptions) => {
  // 1. 返回 Promise 对象
  return new Promise<Data<T>>((resolve, reject) => {
    uni.request({
      ...options,
      // 响应成功
      success(res) {
        // 状态码 2xx,参考 axios 的设计
        if (res.statusCode >= 200 && res.statusCode < 300) {
          // 2.1 提取核心数据 res.data
          resolve(res.data as Data<T>)
        } else if (res.statusCode === 401) {
          // 401错误  -> 清理用户信息,跳转到登录页
          const memberStore = useMemberStore()
          memberStore.clearProfile()
          uni.navigateTo({ url: '/pages/login/login' })
          reject(res)
        } else {
          // 其他错误 -> 根据后端错误信息轻提示
          uni.showToast({
            icon: 'none',
            title: (res.data as Data<T>).msg || '请求错误',
          })
          reject(res)
        }
      },
      // 响应失败
      fail(err) {
        uni.showToast({
          icon: 'none',
          title: '网络错误,换个网络试试',
        })
        reject(err)
      },
    })
  })
}

//my.vue
const getData = async () =>{
  const res = await http<string[]>({
    method: 'GET',
    url: '/home/banner',
  })
  console.log("请求成功", res)
}

添加新文件步骤(如http.ts):

1、在src/utils/文件夹下新建http.ts

2、在vite.config.ts 配置如下:

复制代码
plugins: [uni()],
    resolve: {
    // 配置路径别名
    alias: {
      '@': path.resolve(__dirname, 'src'),
      '@utils': path.resolve(__dirname, 'src/utils'), // 新增这行,映射 @utils 到 src/utils
    },
  },

3、在 tsconfig.json 中同步配置别名:

复制代码
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"],
      "@utils/*": ["src/utils/*"] // 新增这行
    }
  }
}

觉得有帮助的话,打赏一下呗。。

需要商务合作(定制程序)的欢迎私信!!

相关推荐
CHU72903519 小时前
便捷约玩,沉浸推理:线上剧本杀APP功能版块设计详解
前端·小程序
px不是xp1 天前
微信小程序组件化开发最佳实践
微信小程序·小程序·notepad++
软希网分享源码1 天前
中英双语言量化交易投资源码/跟单搬砖区块链交易所源码/前端uniapp纯源码+后端
前端·uni-app·区块链·中英双语言量化交易投资源码
小成Coder1 天前
UniApp 如何调用鸿蒙预加载
uni-app·harmonyos·鸿蒙
编程迪1 天前
基于SpringBoot开发的预约停车系统共享停车位小程序app
小程序·停车场小程序·预约停车·错峰出行·共享车位app
云起SAAS1 天前
早晚安打卡签到小程序完整源码 | 三级分销+红包广告+PC后台 | 商业级系统
小程序
职豚求职小程序1 天前
浙商银行笔试题库小程序练习2026新版题库
小程序
Kingexpand_com1 天前
旅游小程序选型指南:模板与定制开发全解析
小程序·旅游·软件开发·小程序开发·旅游小程序·旅行·定制开发
克里斯蒂亚诺更新1 天前
微信小程序引入vant weapp,button宽度100%
微信小程序·小程序
一品威客网1 天前
租车小程序 APP 版本开发 全端适配高效用车体验一站式搭建
小程序