Basado en el paquete axios ajax

import axios from "axios";
import store from '@/vuex/store';
import * as types from '@/vuex/actions-type'
class AjaxRequest {
  constructor() {
    this.baseURL = "http://allad.huduo.tech/cms/v1"; //api配置
    this.timeout = 3000; //超时
    this.queue = {}; //请求的队列
  }

  setInterceptor(instant, url) {
    //设置请求拦截器
    instant.interceptors.request.use(
      config => {
        //每次请求前,将token放入请求中
        // config.token = localStorage.getItem("token") || "wwwtoken";
        config.headers.token = "wwwtoken";

        //每次请求的时候都拿到取消的请求方法
        let Cancel = axios.CancelToken; //产生一个请求令牌
        //cancelToken挂载在实例上面
        config.cancelToken = new Cancel((c)=> {
          //使用vuex保存
          //请求之前 增加请求队列
          store.commit(types.PUSH_TOKEN, c); // 订阅
        });

        this.queue[url] = url;

        return config;
      },
      error => {
        Promise.reject(error)
      }
    );

    //响应拦截器
    instant.interceptors.response.use(
      res => {
        //对各种状态码进行匹配
        //请求完成后删除对应的url
        delete this.queue[url];
        //正常返回结果
        if (res.data&&res.data.errcode === 0) {
          return res.data.data;
        } else {
          //不是0 的由用户增加决定
          return Promise.reject(res);
        }
      },
      error => {
        delete this.queue[url]; //请求完成删除对应的url
        return Promise.reject(error);
      }
    );
  }

  request(options) {
    let instant = axios.create();
    let config = {
      ...options,
      baseURL: this.baseURL,
      timeout: this.timeout
    };
    this.setInterceptor(instant, options.url);
    return instant(config);
  }
  post(url,options) {
    let instant = axios.create();
    let config = {
      baseURL: this.baseURL,
      timeout: this.timeout
    };
    this.setInterceptor(instant, url);
    return instant.post(url,options,config);
  }
  get(url) {
    let instant = axios.create();
    let config = {
      baseURL: this.baseURL,
      timeout: this.timeout
    };
    this.setInterceptor(instant, url);
    return instant.post(url,config);
  }
}

export default new AjaxRequest();

 

80 artículos originales publicados · Me gusta5 · Visitas 40,000+

Supongo que te gusta

Origin blog.csdn.net/qq_28473733/article/details/103022382
Recomendado
Clasificación