前端优化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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值