axios二次封装的几种方法

一、用Class方法

import axios from "axios";

declare var Promise: any;

export class Request {
  static _instance: Request;

  static getInstance() {
    // tslint:disable-next-line:no-unused-expression
    this._instance || (this._instance = new Request());
    return this._instance;
  }

  config: any;

  constructor() {
    axios.interceptors.request.use(config => {
      // 处理请求数据,如添加Header信息等,
      // 完善url等
      let baseUrl = '';
      config.url = `${baseUrl}${config.url}`;
      return config;
    });
    axios.interceptors.response.use(
      response => {
        // 处理返回数据
        return response.data;
      },
      error => {
        if (error.response.status === 401) {
          // 未登录
        } else if (error.response.status === 400) {
          // 错误信息 alert
        }

        return Promise.reject(error);
      }
    );
  }

  get(url: string, config: object = {}) {
    return axios.get(url, config);
  }

  post(url: string, data: any = {}, config: object = {}) {
    return axios.post(url, data, config);
  }

  put(url: string, data: any, config: object = {}) {
    return axios.put(url, data, config);
  }

  delete(url: string, config: object = {}) {
    return axios.delete(url, config);
  }
}

用法:

import {Request} from "@/utils/request";

const request = new Request();
const res: any = request.post("/iot/configParam", data);

二、取消重复请求

参考链接:https://www.jianshu.com/p/79f5096eaf53

// 默认利用axios的cancelToken进行防重复提交。
// 如需允许多个提交同时发出。则需要在请求配置config中增加 neverCancel 属性,并设置为true

import axios from "axios";
// import store from '@/store/index';
// import { getSessionId } from '@/utils/auth';

/* 防止重复提交,利用axios的cancelToken */
let pending: any[] = []; // 声明一个数组用于存储每个ajax请求的取消函数和ajax标识
const CancelToken: any = axios.CancelToken;

const removePending: any = (config: any, f: any) => {
  // 获取请求的url
  const flagUrl = config.url;
  // 判断该请求是否在请求队列中
  if (pending.indexOf(flagUrl) !== -1) {
    // 如果在请求中,并存在f,f即axios提供的取消函数
    if (f) {
      f("取消重复请求"); // 执行取消操作
    } else {
      pending.splice(pending.indexOf(flagUrl), 1); // 把这条记录从数组中移除
    }
  } else {
    // 如果不存在在请求队列中,加入队列
    if (f) {
      pending.push(flagUrl);
    }
  }
};

/* 创建axios实例 */
const service = axios.create({
  timeout: 5000 // 请求超时时间
});

/* request拦截器 */
service.interceptors.request.use(
  (config: any) => {
    // neverCancel 配置项,允许多个请求
    if (!config.neverCancel) {
      // 生成cancelToken
      config.cancelToken = new CancelToken((c: any) => {
        removePending(config, c);
      });
    }
    // 在这里可以统一修改请求头,例如 加入 用户 token 等操作
    //   if (store.getters.sessionId) {
    //     config.headers['X-SessionId'] = getSessionId(); // 让每个请求携带token--['X-Token']为自定义key
    //   }
    return config;
  },
  (error: any) => {
    Promise.reject(error);
  }
);

/* respone拦截器 */
service.interceptors.response.use(
  (response: any) => {
    // console.log(response)
    // 移除队列中的该请求,注意这时候没有传第二个参数f
    removePending(response.config);
    // 获取返回数据,并处理。按自己业务需求修改。下面只是个demo
    const code = response.code !== undefined ? response.code : response.status;
    if (code !== 200) {
      return Promise.reject("error");
    } else {
      return response;
    }
  },
  (error: any) => {
    // 异常处理
    console.log(error);
    pending = [];
    if (error.message === "取消重复请求") {
      return Promise.reject(error);
    }
    return Promise.reject(error);
  }
);

export default service;

用法:

import request from "@/utils/request";


request({
  method: "GET",
  url: "/api/workflow/getAllUserPermission",
  // params: {
  //   test: 6
  // }
}).then((result) = > {
  // console.log(result)
}).
catch ((err) = > {
  // console.log(err)
});

三、抛出项目所有的请求方法

import axios, {
    AxiosResponse, AxiosRequestConfig
}
from "axios";
import requestConfig from "@/config/requestConfig";
// import {
//   showFullScreenLoading,
//   tryHideFullScreenLoading
// } from "./axiosHelperLoading";
// 公共参数
const conmomPrams: object = {};
class HttpRequest {
    public queue: any; // 请求的url集合
    public constructor() {
        this.queue = {};
    }
    destroy(url: string) {
        delete this.queue[url];
        // 关闭全局的loading...
        if (!Object.keys(this.queue).length) {
            // tryHideFullScreenLoading();
        }
    }
    interceptors(instance: any, url ? : string) {
        // 请求拦截
        instance.interceptors.request.use(
            (config: AxiosRequestConfig) = > {
                // 在请求前统一添加headers信息
                config.headers = {};
                // 添加全局的loading...
                if (!Object.keys(this.queue).length) {
                    // showFullScreenLoading();
                }
                if (url) {
                    this.queue[url] = true;
                }
                return config;
            }, (error: any) = > {
                console.error(error);
            });
        // 响应拦截
        instance.interceptors.response.use(
            (res: AxiosResponse) = > {
                if (url) {
                    this.destroy(url);
                }
                const {
                    data, status
                } = res;
                // 请求成功
                if (status === 200 && data) {
                    return data;
                }
                return requestFail(res);
            },
            // 失败回调
            (error: any) = > {
                if (url) {
                    this.destroy(url);
                }
                console.error(error);
            });
    }
    async request(options: AxiosRequestConfig) {
        const instance = axios.create();
        await this.interceptors(instance, options.url);
        return instance(options);
    }
}
// 请求失败
const requestFail = (res: AxiosResponse) = > {
    let errCode = 408;
    let errStr = "网络繁忙!";
    return {
        err: console.error({
            code: res.data.code || errCode,
            msg: res.data.message || errStr
        })
    };
};
// 合并axios参数
const conbineOptions = (opts: any): AxiosRequestConfig = > {
    const _data = {...conmomPrams, ...opts.data
    };
    const options = {
        method: opts.method || "GET",
        url: opts.url,
        headers: opts.headers
        // baseURL: process.env.VUE_APP_BASE_API,
        // timeout: 5000
    };
    return options.method !== "GET" ? Object.assign(options, {
        data: _data
    }) : Object.assign(options, {
        params: _data
    });
};
const HTTP = new HttpRequest();
/**
 * 抛出整个项目的api方法
 */
const Api = (() = > {
    const apiObj: any = {};
    const requestList: any = requestConfig;
    const fun = (opts: AxiosRequestConfig) = > {
        return async(params: any = {}) = > {
            Object.assign(opts, params);
            const newOpts = conbineOptions(opts);
            const res = await HTTP.request(newOpts);
            return res;
        };
    };
    Object.keys(requestConfig).forEach(key = > {
        let opts = {
            url: requestList[key]
        };
        apiObj[key] = fun(opts);
    });
    return apiObj;
})();
export
default Api as any;

用法:

import Api from "@/utils/request";

export const getKtUploadYxsj = (params = {}) = > {
    return Api.getKtUploadYxsj(params);
};
posted @ 2019-09-30 09:13  放飞的回忆  阅读(4103)  评论(0编辑  收藏  举报