vue+eleui项目 项目结构(封装一个可全局调用的http请求)

严格前后端分离,接口路径统一存放于一个文件中

1.创建一个httpRequest.js文件封装一个axios

export class HttpRequest {
  constructor(header) {
    if (!axios) throw 'axios is not defined!';
    this.instance = axios.create({
      headers: {
        '_uuid': $utils.uuid,
        'dataType': 'json',
        'Cache-Control': 'no-cache',
        'X-Requested-With': 'XMLHttpRequest',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        // version: process.env.VERSION,
      },
      cache: false, //  不要缓存
      responseType: 'json', // 默认的
      timeout: 20000,  //超时时间
      transformRequest: [(data) => new URLSearchParams(data)],  //序列化参数
    });
    this.setHeader(header);

    /** 取消 Cancellation*/
    this.source = axios.CancelToken.source;
    this.UnResolveCollections = {};
  }

  /** @headers 自定义请求头*/
  setHeader = (headers = {}) => {
    Object.assign(
      this.instance.defaults.headers,
      headers
    );
  };

  /** GET*/
  get = (url, params, config = {}) => {
    if (config.cancel) {
      config.cancelToken = this.unResolveHandle(url);
    }
    return this.instance.get(url, {params, ...config})
      .then(res => this.onResolveHandle(res, url));
  };

  /** POST*/
  post = (url, params, config = {}) => {
    if (config.cancel) {
      config.cancelToken = this.unResolveHandle(url);
    }
    return this.instance.post(url, params, config)
      .then(res => this.onResolveHandle(res, url));
  };

  // 创建取消token
  creatCanelToken = url => {
    if (_.isEmpty(url)) throw new Error('url 不能为空');
    let source = this.source();
    this.UnResolveCollections[url] = {
      source,
      cancelToken: source.token
    };
    return source.token;
  };

  // 是否已经在请求列表
  hasRequest = url => {
    return Reflect.has(this.UnResolveCollections, url);
  };

  // 取消/删除 请求
  removeRequest = (url, type = 'cancel') => {
    switch (type) {
      case 'cancel':
        this.UnResolveCollections[url].source.cancel('abort');
        break;
      case 'del':
        Reflect.deleteProperty(this.UnResolveCollections, url);
        break;
    }
  };

  // 未返回请求结果的 防止重复请求
  unResolveHandle = url => {
    if (this.hasRequest(url)) {
      this.removeRequest(url, 'cancel');
    }
    return this.creatCanelToken(url);
  };

  // 请求返回后,从本地集合中删除这个链接
  onResolveHandle = (res, url) => {
    if (!_.isEmpty(res)) {
      this.hasRequest(url) && this.removeRequest(url, 'del');
    }
    return res;
  };
}

2.创建一个config-http.js文件 ,引入之前的httpRequest.js

import {HttpRequest} from "../plugins/httpRequest";

export class HttpConfig extends HttpRequest {
  /**
   * @HttpRequest 请求插件
   * @header 请求头
   * @responseUse 添加响应拦截器方法*/
  constructor(responseUse) {
    super();
    // 添加响应拦截器
    this.instance.interceptors.response.use(
      responseUse.resolve,
      error => responseUse.reject(error, this)
    );
  }
  homeList = (data, config) => {  
    return this.get('/request/homeList', data, config);
  };
  withdrawOfTh = (data, config) => { 
    return this.post('/request/drawOrder/createDrawOrder', data, config);
  };
}

3.创建一个setting-http.js,引入之前的config-http.js

import {HttpConfig} from "../../../__factory__/middleware/config-http";
export default {
  install(Vue) {
    const $_http = new HttpConfig(
      {
        resolve: (response) => Promise.resolve(response.data),
        reject: (error, http) => {
          if (error.__CANCEL__) {
            return Promise.reject({
              status: -1,
              msg: 'aborted',
            });
          }
          let {request, message, config} = error;
          console.log(request, message, config);
          let {status = ''} = request;

          if (/timeout/.test(message)) {
            return http.instance(config);
          }

          if (status === 401) {
            $utils.storage.remove('token');
            $utils.storage.remove('customerInfo');
            location.href = $url.login;
            return;
          }
          if (status === 404) {
            console.error(`${config.url} not found`);
          }
          if (status >= 500) {
            console.error(`error code is: ${status}, the server isn't responding.`);
          }
          return Promise.reject({
            status: -1,
            msg: message,
            uuid: $utils.uuid,
            requestStatus: status,
            url: config.url,
          });
        }
      }
    );
    window.$http = $_http;
    Vue.prototype['$_http'] = $_http;
  }
};

4.在需要的页面引入setting-http.js

homeList() {
  this.$_http.homeList().then(res => {
     if (res.status !== 0) {
        return this.$message.error(res.msg);
      }
  });
},

猜你喜欢

转载自blog.csdn.net/qq_24510455/article/details/82226773
今日推荐