小程序/uniapp封装请求

手撸一个简单版的axios

export default class Axios {
  constructor(config) {
    if (!Axios.instance) {
      Axios.instance = this;

      // 请求配置
      this.config = {
        baseUrl: "", // 基础路径
        timeout: 30 * 1000, // 超时时间
        ...config,
      };
      // 响应会调方法
      this.responseResovle = (data) => data;
      // 请求执行回调
      this.requestResovle = (data) => data;
      // 响应错误回调
      this.responseError = (data) => data;
      // 拦截器
      this.intercept = {
        request: {
          use: (resolve, error) => {
            try {
              if (
                typeof resolve !== "function" ||
                (error && typeof error !== "function")
              ) {
                throw new Error("此方法应该接收两个函数");
              }
              this.requestResovle = resolve;
            } catch (e) {
              if (error) return error(e);
              throw new Error(e || "参数错误");
            }
          },
        },
        response: {
          use: (resolve, error) => {
            if (
              typeof resolve !== "function" ||
              (error && typeof error !== "function")
            ) {
              throw new Error("此方法应该接收两个函数");
            }
            resolve && (this.responseResovle = resolve);
            error && (this.responseError = error);
          },
        },
      };
    }
    return Axios.instance;
  }
  // 静态-获取实例方法
  static getInstance(config) {
    if (!this.instance) {
      return (this.instance = new Axios(config));
    }
    return this.instance;
  }

  // 重新发送方法
  reSend = (options, resolve, reject) => {
    console.log("reSend", options);
    return uni.request({
      ...options,
      success: (res) => {
        resolve(this.responseResovle(res));
      },
      fail: (e) => {
        reject(this.responseError(e));
      },
    });
  };

  // 发送
  send = (args) => {
    let config = {};
    if (typeof args === "object") {
      config = {
        ...JSON.parse(JSON.stringify(this.config)),
        ...args,
      };
    }

    config = this.requestResovle(config); // 将config交给拦截器回调函数
    return new Promise((resolve, reject) => {
      config = {
        ...config,
        url: config.baseUrl + (config.url || ""),
        method: config.method.toUpperCase(), // 配置method方法
      };
      uni.request({
        ...config,
        success: (res) => {
          resolve(
            this.responseResovle({
              ...res,
              config: config,
            })
          );
        },
        fail: (e) => {
          reject(
            this.responseError({
              ...res,
              config: config,
            })
          );
        },
      });
    }).catch((e) => {
      return e;
    });
  };
}

使用方法

// 单例模式-创建Axios实例
let axios = new Axios.getInstance({
  timeout: 30 * 1000,
  baseUrl: BASE_URL + apiUrl,
});

/**
 * @param {*} options,
 * @returns Promise
 */
axios.post = (options) => {
  return axios.send({
    ...options,   
     method: "post",
  });
};

/**
 * @param {*} options,
 * @returns Promise
 */
axios.get = (options) => {
  return axios.send({
    ...options,  
    method: "get",
  });
};

// 请求拦截
axios.intercept.request.use((config) => {
  // to do something
  return config;
});

// 响应拦截
axios.intercept.response.use(
  (res) => {
    // to do something
    return res
  },
  (res) => {
    return {
      meta: {
        code: 400,
        msg:  res?.meta?.msg
      },
    };
  }
);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值