Several methods of secondary packaging axios

First, the method by 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 =the baseUrl} $ {$ `{}` config.url;
       return config; 
    }); 
    axios.interceptors.response.use ( 
      Response => {
         // returns the process data 
        return response.data; 
      }, 
      error => {
         IF (error === 401 .response.status ) {
           // unregistered 
        } the else  IF (error.response.status === 400 ) {
           // error message 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);
  }
}

usage:

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

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

Second, repeat request cancellation

import axios from 'axios'
import store from '../store'
import router from '../router'
// 请求列表
const requestList = []
// 取消列表
const CancelToken = axios.CancelToken
let sources = {}
// axios.defaults.timeout = 10000
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'
axios.defaults.baseURL = process.env.BASE_URL
axios.interceptors.request.use((config) = > {
    const request = JSON.stringify(config.url) + JSON.stringify(config.data)
    config.cancelToken = new CancelToken((cancel) = > {
        sources[request] = cancel
    })
    if (requestList.includes(request)) {
        sources[request]('取消重复请求')
    } else {
        requestList.push(request)
        store.dispatch('changeGlobalState', {
            loading: true
        })
    }
    const token = store.getters.userInfo.token
    if (token) {
        config.headers.token = token
    }
    return config
}, function(error) {
    return Promise.reject(error)
})
axios.interceptors.response.use(function(response) {
    const request = JSON.stringify(response.config.url) + JSON.stringify(response.config.data)
    requestList.splice(requestList.findIndex(item = > item === request), 1)
    if (requestList.length === 0) {
        store.dispatch('changeGlobalState', {
            loading: false
        })
    }
    if (response.data.code === 900401) {
        window.ELEMENT.Message.error('认证失效,请重新登录!', 1000)
        router.push('/login')
    }
    return response
}, function(error) {
    if (axios.isCancel(error)) {
        requestList.length = 0
        store.dispatch('changeGlobalState', {
            loading: false
        })
        throw new axios.Cancel('cancel request')
    } else {
        window.ELEMENT.Message.error('网络请求失败', 1000)
    }
    return Promise.reject(error)
})
const request = function(url, params, config, method) {
    return new Promise((resolve, reject) = > {
        axios[method](url, params, Object.assign({}, config)).then(response = > {
            resolve(response.data)
        }, err = > {
            if (err.Cancel) {
                console.log(err)
            } else {
                reject(err)
            }
        }).
        catch (err = > {
            reject(err)
        })
    })
}
const post = (url, params, config = {}) = > {
    return request(url, params, config, 'post')
}
const get = (url, params, config = {}) = > {
    return request(url, params, config, 'get')
}
export {
    sources, post, get
}

usage:

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

const res: any = post("/iot/configParam", data);

Third, all of the items thrown request method

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];
         // close the global ... loading 
        IF (Object.keys (! the this .queue) .length) {
             // tryHideFullScreenLoading (); 
        } 
    } 
    interceptors (instance: the any, url ? : String) {
         // request interception 
        instance.interceptors.request.use ( 
            (config: AxiosRequestConfig) => {
                 // unified information before the request headers added 
                config.headers = {};
                 // add global ... loading 
                IF (Object!. Keys ( the 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;

usage:

import Api from "@/utils/request";

export const getKtUploadYxsj = (params = {}) = > {
    return Api.getKtUploadYxsj(params);
};

Guess you like

Origin www.cnblogs.com/ziyoublog/p/11610958.html