axios封装

axios封装importaxiosfrom'axios'importQsfrom'qs'//(如果只是get请求就不需要引qs)//序列化插件importmd5from'js-md5';//加密插件importrouterfrom&#

大家好,欢迎来到IT知识分享网。axios封装"

import axios from 'axios'
import Qs from 'qs'//(如果只是get请求就不需要引qs)//序列化插件
import md5 from 'js-md5';//加密插件
import router from '../src/router/index'
import JSONbig from 'json-bigint'
import messages from '../src/components/commonjs/common';
import {Loading} from 'element-ui'
import _ from 'lodash'//这里时用的防抖函数
import Vue from 'vue';
let loadingInstance; //loading 实例
let needLoadingRequestCount = 0; //当前正在请求的数量
axios.defaults.withCredentials = false;  //false  不跨域  true 跨域 //是否允许携带cookie跨域
export default function(path, params, method = "GET", headerType = "json"){
  let pending = []; // 声明一个数组用于存储每个请求的取消函数和axios标识
  let cancelToken = axios.CancelToken;//用于取消已发送的请求
  let removePending = (config) => {
    for (let i in pending) {
      if (pending[i].url === config.url.split('?')[0]) { // 在当前请求在数组中存在时执行取消函数
        pending[i].f(); // 执行取消操作
        pending.splice(i, 1); // 把pending记录删掉
      }
    }
  }
    let data = {};//baseURL = ""
    let arrs = ['LoginUser','SendVerifyCode','GetEnterpriseListByTel','GetCompanys','SelectCompany','Logout']
    function getfilter(){
      return arrs.filter(item=>{
          return path.indexOf(item)>-1
      })
    }
    for(var i in params){//去除参数的空格
      if (params.hasOwnProperty(i) === true){  
        if(typeof params[i] == 'string'){
          if(params[i] !=''){
            params[i] = params[i].trim();
          }
          // this.accountSearch[i] = this.accountSearch[i].trim();
        }         
      } 
    }
    let loading;
    function showLoading() {
        // card__body
        //loadingInstance = null;
       let main = document.querySelector('.el-card')
       if (main) {
          if (needLoadingRequestCount === 0 && !loadingInstance) {
             loadingInstance = Loading.service({ 
                 target: main, text: '正在加载...', background: 'rgba(255,255,255,255,.7)' 
             });
          }
          needLoadingRequestCount++;
       }
    }
    function closeLoading() {
       Vue.nextTick(() => { // 以服务的方式调用的 Loading 需要异步关闭
          needLoadingRequestCount--;
          needLoadingRequestCount = Math.max(needLoadingRequestCount, 0); // 保证大于等于0
          if (needLoadingRequestCount === 0) {
             if (loadingInstance) {
                hideLoading()
             }
          }
       });
    }
    var hideLoading = _.debounce(() => {//防抖
        loadingInstance.close();
        loadingInstance = null;
     }, 300);
    let token = '';
    var strCookies = document.cookie;
    strCookies = strCookies.replace(/\s*/g,"");//去空格
        //截取变成cookie数组
        var array = strCookies.split(';');
        for (let i = 0; i < array.length; i++) {
            //将cookie截取成两部分
            var item = array[i].split("=");
            //判断cookie的name 是否相等
            if (item[0] == 'access_token') {
                axios.defaults.headers['Access-Token'] =  item[1];
                localStorage.setItem('Token',item[1]);
            }
        }
    if(getfilter().length<=0){
        var usermsg = JSON.parse(localStorage.getItem('usermsg'))||'';
            axios.defaults.headers['Authorization'] = md5(usermsg.LoginUserID + localStorage.getItem('TokenStr'))+ '&'+new Date().getTime().toString()+'&'+usermsg.LoginUserID;
            
    }else{

    }
      //设置请求头
    if (method === 'POST') {   //post请求
        if (headerType === "json") {
            axios.defaults.headers["Content-Type"] = 'application/json;charset=UTF-8'
            data = params
        } else{
            axios.defaults.headers["Content-Type"] = 'application/x-www-form-urlencoded;charset=UTF-8'
            data = Qs.stringify(params);
        }
    }else if(method === 'GET'){
        axios.defaults.headers["X-Requested-With"] = 'XMLHttpRequest';
        axios.defaults.headers["Access-Control-Allow-Origin"] = "*";
        if (headerType == !'json') {
            axios.defaults.headers["Content-Type"] = 'application/x-www-form-urlencoded;charset=UTF-8'
            axios.defaults.headers["Access-Control-Allow-Origin"] = "*";
        }
        data = Qs.stringify(params);
        path = path + '?' + data
        data = {};
    }

    let headers = axios.defaults.headers;
     // 请求拦截
    axios.interceptors.request.use(function (config) {
        showLoading();
        removePending(config); // 在一个axios发送前执行一下判定操作,在removePending中执行取消操作
        if(config.url.indexOf('Channel/SearchOne')<=-1){//在企业详情页 必须请求两次不同的数据
          config.cancelToken = new cancelToken(function executor (c) { // 本次axios请求的配置添加cancelToken
              pending.push({
                url: config.url.split('?')[0],
                f: c
              });
          })
        }
        return config;
       }, function (error) {
        return Promise.reject(error);
       });

      //响应拦截
      axios.interceptors.response.use(response=>{
          closeLoading();
        removePending(response.config); // 在一个axios响应后再执行一下取消操作,把已经完成的请求从pending中移除
        return response
           },err=>{
            closeLoading();
            if (err && err.response) {
                switch (err.response.status) {
                  case 400: 
                  err.message = err.response.data.detail.issue;
                  messages.message.error(err.message)
                   break;
                  case 401: 
                    localStorage.setItem('UserName','')
                    localStorage.setItem('ispagehead','')
                    localStorage.setItem('QYMC','')
                    localStorage.setItem('QYID','')
                    localStorage.setItem('isLogin','0')
                    localStorage.setItem('isLogins','0')
                    var exdate = new Date();                   
                    exdate.setDate(exdate.getDate()  -1);
                    window.document.cookie = 'access_token=;path=/;expires='+exdate.toGMTString()
                    localStorage.setItem('usermsg','')
                    localStorage.setItem('TokenStr','')
                    localStorage.setItem('AccessToken','')
                    router.push({ path: '/'}); 
                    if(err.response.config.url.indexOf('Login/GetLoginUserInfo')>-1){
                    }else{
                        err.message = '登陆过期,请重新登录';
                        messages.message.error(err.message)
                    }
                    break;
                  case 403: 
                    if(err.response.config.url.indexOf('Channel/GetAllSelect')>-1){
                    }else{
                        messages.message.error(err.message)
                    }
                    break;
                  case 404: 
                    messages.message.error('请求出错(404)') 
                    break;
                  case 408: 
                    messages.message.error('请求超时(408)') 
                    break;
                  case 412: 
                    router.push({ path: '/SelectCompany'});
                    break;
                  case 470:
                    err.message = err.response.data.detail.issue;
                    messages.message.error(err.message)
                    break;
                  case 500: 
                    //messages.message.error('服务器错误(500)') 
                    break;
                  case 501:
                    // messages.message.error('服务未实现(501)') 
                    break;
                  case 502: 
                    messages.message.error('网络错误(502)') 
                    break;
                  case 503: 
                    messages.message.error('服务不可用(503)') 
                    break;
                  case 504: 
                    messages.message.error('网络超时(504)') 
                    break;
                  case 505: 
                    messages.message.error('HTTP版本不受支持(505)') 
                    break;
                }
            }else if (err.__CANCEL__) {
             //messages.message.error('操作过于频繁,稍后重试')
            } else {
              messages.message.error('连接服务器失败')
            }
            return Promise.reject(err)
        })
    
const request = axios.create({
    transformResponse: [function (data) {
      return data//JdSONbig.parse(data)
    }],
})
       //发送请求
      return new Promise((resolve,reject)=>{
        axios({
            url:path,
            method,
            data:params,
            timeout:60000,
            }).then(result=>{
                resolve(result.data)
            }).catch(err=>{
              console.log(err.message)
                if(err.message == 'Request failed with status code 401'){
                    localStorage.setItem('UserName','')
                    localStorage.setItem('ispagehead','')
                    localStorage.setItem('QYMC','')
                    localStorage.setItem('QYID','')
                    localStorage.setItem('isLogin','0')
                    localStorage.setItem('isLogins','0')
                    var exdate = new Date();                   
                    exdate.setDate(exdate.getDate()  -1);
                    window.document.cookie = 'access_token=;path=/;expires='+exdate.toGMTString()
                    localStorage.setItem('usermsg','')
                    localStorage.setItem('TokenStr','')
                    localStorage.setItem('AccessToken','')
                    router.push({ path: '/'})
                }else if(err.message == 'Request failed with status code 412'){
                    router.push({ path: '/SelectCompany'})
                }else{
                    reject(err)
                }
            })
         })
}

 

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/30777.html

(0)

相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注微信