axios 封装

后台的开发方式不同导致很多细节性差异,此封装仅供参考
 
import axios from 'axios'
import store from '../../store.js'
import router from '../../router.js'
import qs from 'qs'
import { Loading, Message } from 'element-ui';
var loadingInstance;// 显示loading
var reqCount = 0;//请求数
 
axios.interceptors.request.use(function (config) {
 
  let token = sessionStorage.getItem('token');
  if (token && typeof token !== 'undefined') {
    config.headers.token = token;
  }
  return config;
}, function (err) {
  return Promise.reject(err);
})
// 添加响应拦截器
axios.interceptors.response.use(function (res) {
  reqCount--;
  if (reqCount <= 0) {
    loadingInstance.close();
  }
  if (res.headers.token && typeof res.headers.token !== 'undefined') {
    sessionStorage.setItem('token', res.headers.token);
  }
  // 生成文件
  if (res.headers['content-type'].indexOf('application/octet-stream') == -1 && !res.data.error) {
    let reader = new FileReader();
    reader.readAsText(res.data);
    return new Promise((resolve) => {
      reader.onload = function () {
        let result = JSON.parse(reader.result);
        resolve(result);
      };
    });
  }
  return res.data
}, function (err) {
  reqCount--;
  if (reqCount <= 0) {
    loadingInstance.close();
  }
  return Promise.reject(err);
})
//需要重新登录--------------------------------------------------------------------------------------
function goLogin() {
  sessionStorage.clear();
  store.dispatch('setIsLoginDialog', true)
}
// 封装axios--------------------------------------------------------------------------------------
/**
 * @params method  String POST
 * @params url     String 地址
 * @params params  String 接口所需传参
 * @params Deal    String 是否需要进行状态码判断操作,为了处理不需要登录的页面调用了需要登录才能使用的接口返回的状态码导致的错误流程处理
 * @params config  Object axios中配置参数,目前是为了处理一些接口调用不需要loading小菊花的问题
 * */
function apiAxios(method, url, params, Deal,config) {
   let baseURL = '';
//开发模式、测试模式及生产模式
  if(process.env.NODE_ENV !== 'development'){
    if(url.indexOf('/host')>-1){
      baseURL = process.env.VUE_APP_CASTLE_URL;
      url = url.replace('/host','');
    }else if(url.indexOf('/sHost')>-1){
      baseURL = process.env.VUE_APP_SCTCC_URL;
      url = url.replace('/sHost','');
    }else{
      baseURL = process.env.VUE_APP_HZW_URL;
      url = url.replace('/host','');
    }
  }
  params = params || {};
  //处理pageNo参数(接口问题)
  if (params.pageNo && params.pageNo > 0) {
    params.pageNo -= 1;
  }
  config = config || {
    // 请求前
    transformRequest: [function (data) {
      reqCount++;
      loadingInstance = Loading.service({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      return data;
    }],
  }
  let httpDefault = Object.assign({}, config, {
    method: method,
    baseURL: baseURL,
    url: url,
    params: method === 'GET' || method === 'DELETE' ? params : null,
    data: method === 'POST' || method === 'PUT' ? qs.stringify(params) : null,
    timeout: 20000
  });
  //上传文件(接口需求)
  if (params.file && params.catalog) {
    let fileData = new FormData();
    fileData.append('file', params.file);
    fileData.append('catalog', params.catalog);
    if (params.is_public_read) {
      fileData.append('is_public_read', params.is_public_read);
    }
    httpDefault.data = fileData;
  }
   //如果设置了响应数据类型
  if (params.responseType) {
    httpDefault.responseType = params.responseType;
  }
  return new Promise((resolve, reject) => {
    axios(httpDefault)
      .then((res) => {
        if(Deal){
          resolve(res);
          return
        }
        //0代表正常,1代表未登录和登陆失效,2代表程序异常,3没有权限
        if (res.error.err_code === 0) {
          resolve(res);
        } else if (res.error.err_code === 1) {
          Message.error(res.error.err_msg);
          goLogin();
        } else if (res.error.err_code === 2 || res.error.err_code === 3) {
          Message.error(res.error.err_msg);
          resolve(res);
        } else {
          reject(res);
        }
      }).catch((err) => {
        Message.error('系统错误');
      })
  })
}
export default {
  apiAxios
}
原文地址:https://www.cnblogs.com/92xcd/p/9933493.html