uni+vue3请求响应拦截器(js/ts)

一、uni+vue3+js请求响应拦截器

新建utils文件夹,下面新建request.js

let baseUrl = 'http://域名:端口'
export default {
  request(options){
    return new Promise((resolve, reject) => {
      options.url = baseUrl + options.url;
      options.complete = (response) => {
        if (response.statusCode == 200 || response.statusCode == 0) {
          if (response.data.code == 500) {
            uni.showToast({
              title: response.data.msg,
              icon: "none",
              duration: 2000,
            });
          }
          resolve(response.data);
        } else {
          uni.showToast({
            title: "请求异常",
            icon: "none",
          });
        }
      };
      uni.request(options);
    });
  },

  post(url, data, header){
    let options = {
      url: url,
      data: data,
      header: header,
      method: "POST",
    };

    return this.request(options);
  },

  get(url, data, header) {
    let options = {
      url: url,
      data: data,
      header: header,
    };

    return this.request(options);
  },
};

在mian.js中引入request.js文件


import request from "./utils/request.js";
import { createSSRApp } from 'vue'
export function createApp() {
  const app = createSSRApp(App)
  app.config.globalProperties.$Api = request;
  app.use(uviewPlus)
  return {
    app
  }
}

页面中使用

import {ref, getCurrentInstance} from "vue";
const internalInstance  = getCurrentInstance()
const globalProperties = internalInstance.appContext.config.globalProperties
const $Api= globalProperties.$Api


const getInfo = () => {
      $Api.get(接口地址, 传递参数, 请求头配置).then(res => {
        //对接口数据进行操作
    }).catch(() => {

    }).finally(() => {

    }) 
}

二、uni+vue3+ts请求响应拦截器

新建utils文件夹,下面新建request.ts

方法一:

cosnt baseUrl = 'xxxx'
interface Options {
  url: string;
  data?: any;
  header?: any;
  method?: string;
  complete?: (response: any) => void;
}
interface ResponseData {
  code: number;
  msg: string;
}
export default {
  request(options: Options = {}): Promise<any> {
    return new Promise((resolve, reject) => {
      let url = options.url;
      if (!(url.indexOf("http://") !== -1 || url.indexOf("https://") !== -1)) {
        options.url =  'http://' + baseUrl + "/app/"+ url;
      }
      options.header.token = uni.getStorageSync("token");
      options.complete = (response) => {
        if (response.statusCode == 200 || response.statusCode == 0) {
          if (response.data.code == 401 || response.data.code == 420) {          
            uni.navigateTo({
              url: "/pages/login/login",
            });                   
          }
          if (response.data.code == 500) {
            uni.showToast({
              title: response.data.msg,
              icon: "none",
              duration: 2000,
            });
          }
          resolve(response.data);
        } else {
          uni.showToast({
            title: "请求异常",
            icon: "none",
          });
        }
      };
      uni.request(options);
    });
  },

  post(url: string, data: any = {}, header: any = {}): Promise<any> {
    let options: Options = {
      url: url,
      data: data,
      header: header,
      method: "POST",
    };

    return this.request(options);
  },

  get(url: string, data: any = {}, header: any = {}): Promise<any> {
    let options: Options = {
      url: url,
      data: data,
      header: header,
    };

    return this.request(options);
  },
};

方法二:

cosnt baseUrl = 'xxxx'

// 添加拦截器
const httpInterceptor = {
    //拦截前触发
    invoke(options:UniApp.RequestOptions) {
        //非http开头需拼接地址
        if (!options.url.startWith('http')) { 
            options.url = baseUrl + options.url
        }
        // 请求超时,默认60s
        options.timeout = 10000
        //添加小程序端请求头标识,header默认是对象格式
        options.header = {
            ...options.header,
           'source-client':'miniapp' 
        }
        //添加toke请求头标识
        const token = uni.getStorageSync("token")
        options.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) => { 
    //返回Peomise对象
    return new Promise<Data<T>>((resolve, reject) => { 
        uni.request({
            ...options,
            //请求成功
            success(res) { 
                if (res.statusCode >= 200 && res.statusCode < 300) {
                    //获取数据成功,调用resolve
                resolve(res.data as Data<T>)//类型断言为更准确的类型

                } else if (res.statusCode == 401) {
                   // 401错误,token失效,清除本地存储中的token,跳转到登录页,调用reject
                    uni.removeStorage({
                        key: 'token',
                        success: function (res) {
                            console.log('成功删除 token');
                            uni.navagateTo({
                                url: '/pages/login/login'
                            })
                            reject(res)
                        },
                    })
                } else { 
                    //通用错误,根据后端错误信息轻提示,调用reject
                    uni.showToast({
                        icon: 'none',
                        title:(res.data as Data<T>).msg||'请求错误'
                    })
                    reject(res)
                }
            },
            fail(err) {
                //网络错误,调用reject
                    uni.showToast({
                        icon: 'none',
                        title:'网络错误'
                    })
                    reject(err) 
             }
            
        })
    })
}

引入及页面使用同上

  • 9
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值