uniapp(vue3+ts+pinia)请求拦截器封装及使用

本文介绍了如何使用Vue.js的Pinia库存储用户信息和token,创建一个http拦截器处理请求,包括添加请求头、超时和错误处理。还展示了如何在uni-app中使用这些工具,如getMemberProfileAPI和putMemberProfileAPI进行API调用。
摘要由CSDN通过智能技术生成

1.准备工作

        通过pinia存储用户信息及token值(可借鉴Pinia的使用

2.代码

在src目录下创建一个utils文件src/utils/http.ts

import { useMemberStore } from "@/stores";

const baseURL = ""

// 添加拦截器
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 = {
            ...options.header,
            "source-client": "miniapp"
        }
        // 4.添加token请求头标识
        const menberStore = useMemberStore()
        const token = menberStore.profile?.token
        if (token) {
            options.header.Authorization = token
        }

        // console.log(options);
    }
}
uni.addInterceptor('request', httpInterceptor)
uni.addInterceptor('uploadFile', httpInterceptor)


interface Data<T> {
    code: string,
    msg: string,
    result: T
}
// 添加类型,支持泛型
export const http = <T>(options: UniApp.RequestOptions) => {
    // 返回Promise对象
    return new Promise<Data<T>>((resolve, reject) => {
        uni.request({
            ...options,
            // 2.请求成功
            success(res) {
                // console.log(res);
                
                if (res.statusCode >= 200 && res.statusCode < 300) {
                    resolve(res.data as Data<T>);
                } else if (res.statusCode === 401) {
                    // 401错误 -> 清理用户信息,跳转到登录页
                    const menberStore = useMemberStore()
                    menberStore.clearProfile()
                    uni.navigateTo({ url: "/pages/login/login" })
                    reject(res)
                } else {
                    // 其他错误
                    uni.showToast({
                        icon: 'none',
                        title: (res.data as Data<T>).msg || '请求错误'
                    })
                    reject(res)
                }
            },
            // 3.请求失败
            fail(err) {
                uni.showToast({
                    title: '网络错误',
                    icon: 'none'
                })
                reject(err)
            }
        })
    })
}

3.使用

在src目录下创建一个api文件src/api/login.ts

import { http } from '@/utils/http'

/**
 * 获取个人信息
 */
export const getMemberProfileAPI = () => {
  return http({
    method: 'GET',
    url: '/member/profile',
  })
}

/**
 * 修改个人信息
 * @param data 请求体参数
 */
export const putMemberProfileAPI = (data) => {
  return http({
    method: 'PUT',
    url: '/member/profile',
    data,
  })
}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值