前端优化http请求,使用axios如何取消重复请求

const axios = require('axios');
const qs    = require('qs');

import store from "./store"

class Http {
  constructor() {
    // 请求的基础路径
    this.baseURL ="";
    // 超时时间
    this.timeout = 6000;
    this.queue = new Map(); // 存放每一次的请求
    this.refresh = false

  }

  addPending(instance,config) {
    const url          = [
      config.method,
      config.url,
      qs.stringify(config.params),
      qs.stringify(config.data)
    ].join("&");

    config.cancelToken = config.cancelToken|| new instance.CancelToken(cancel => {
      if (!this.queue.has(url)){
        this.queue.set(url,cancel);
      }
    });
  }

  removePending(instance,config) {
    if (config){
      const url          = [
        config.method,
        config.url,
        qs.stringify(config.params),
        qs.stringify(config.data)
      ].join("&");
      if (this.queue.has(url)) {
        const cancel = this.queue.get(url);
        cancel(url);
        this.queue.delete(url);
      }
    }
  }

  clearPending() {
    for (const [url, cancel] of this.queue) {
      cancel(url);
    }
    this.queue.clear();
  }

  setInterceptor(instance,url) {
    instance.interceptors.request.use(async (config) => {
      this.removePending(instance,config);
      this.addPending(instance,config);
      //检测token
      if (store.state.token) {
          config.headers['Token'] = store.state.token;
      }
      return config;
    },error => {
      Promise.reject(error);
    });

    instance.interceptors.response.use((response) => {
      this.removePending(response.config);
      return response.data;
    },error => {
      if (instance.isCancel&&instance.isCancel(error)) {
        console.log('repeated request: ' + error.message)
      }else {
        console.log('other: ' + error.message)
      }
      Promise.reject(error);
    });
  }

  //设置参数
  merge(options) {
    return {...options,baseURL:this.baseURL,timeout:this.timeout}
  }

  createInstance(options) {
    let instance = axios.create();
    instance.CancelToken = axios.CancelToken;
    this.setInterceptor(instance,options.url);
    let config = this.merge(options);
    return instance(config)
  }

  post(options) {
    let ops = {
      url:'',
      method:'post'
    };
    if (typeof options === 'string') {
      ops.url = options;
    }else {
      ops = {...ops,options}
    }
    return this.createInstance(ops);
  }

}


export default new Http
发布了80 篇原创文章 · 获赞 5 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/qq_28473733/article/details/104788976