axios http配置-拦截器

axios全局配置axios.js文件 

/**
 * http配置
 */
// 引入axios以及layer中的loading和message组件
import axios from 'axios'

// 获取CancelToken
const CancelToken = axios.CancelToken;
const source = CancelToken.source();

// 拦截器
export let myInterceptor = null;
export function setInterceptor(callback){
  myInterceptor =  axios.interceptors.request.use(config => {
    config.cancelToken = source.token;
    if(callback){
      // source.cancek() // 取消请求
      return callback(config,source);
    }
    else{
      config.loadinginstace = layer.open({type: 2,shadeClose:false});
      return config
    }
  // return config
  }, error => {
    layer.open({
      content: '加载超时'
      ,skin: 'msg'
      ,time: 3 //2秒后自动关闭
    });
    setTimeout(() => {
     // layer.close(loadinginstace)
      layer.closeAll();
    },3000)
    return Promise.reject(error)
  })
}

// 超时时间
axios.defaults.timeout = 15000;
// http请求拦截器
let loadinginstace

// http响应拦截器
axios.interceptors.response.use(data => {// 响应成功关闭loading
  layer.close(data.config.loadinginstace)
  return data
}, error => {
  layer.open({
    content: '请求失败'
    ,skin: 'msg'
    ,time: 3 //2秒后自动关闭
  });
  setTimeout(() => {
    layer.closeAll();
  },3000);
  return Promise.reject(error)
})

export default axios;

post方法封装axios.service.js

import axios, {setInterceptor,myInterceptor} from './axios';
setInterceptor((config)=>{return config});

class SllAxios{
   getUrl(url) {
    return `${process.env.BASE_URL?process.env.BASE_URL:__ce.baseURL}${url}`;
    //  return `/api${url}`; // 防止跨域,开发环境用这个代理
  };

  //公共ajax;
  postServer(opt) {
    if(opt.resetInterceptor){ // 默认false     true:移除拦截器,false:不移除拦截器
      myInterceptor?axios.interceptors.request.eject(myInterceptor):''; // 移除拦截器
      setInterceptor((config,source)=>{
        opt.resetInterceptor(source);
       // console.log('拦截器自定义loading')
        return config;
      });
    }else{
      myInterceptor?axios.interceptors.request.eject(myInterceptor):''; // 移除拦截器
      setInterceptor();
    }
    let data = {};
    if (opt.data) {
      data = opt.data;
    }
    axios.post(opt.url, data).then((response) => {
      const info = response.data;
      if(info.ResultCode === 0){ // 失败            
        layer.closeAll();
          if(info.Msg){
            layer.open({
              content:info.Msg
              ,skin: 'msg'
              ,time: 4 //2秒后自动关闭
            });
          }
      }
      if(info.ResultCode === 1){ // 成功 Data有值
        if (opt.onSuccess) {
          opt.onSuccess(info.Data,info);
        }
      }
     
    }).catch(error => {
      console.log(error)
      if (opt.onFailed) {
        opt.onFailed(error,'error');
      }    
    });
  }

  setData(opt) {
    let data = {};
    if (opt.data) {
      data = opt.data;
    }
    return data;
  }
  setInterceptor(opt){
    return opt.resetInterceptor?opt.resetInterceptor:false
  }
}

export default SllAxios;

接口的封装文件,otherServer.js:

import SllAxios from  './axios.service'
const sllAxiosMethods = new SllAxios();
class OtherServer{
  // 页面跳转链接(国际机票跳到首页和支付页面)
  sendBaseLinksServer(opt){
    const data = sllAxiosMethods.setData(opt);
    const url = sllAxiosMethods.getUrl('/Base/Links'); // /Query/Stations
    sllAxiosMethods.postServer({url, data, onSuccess: opt.onSuccess, onFailed: opt.onFailed,resetInterceptor:sllAxiosMethods.setInterceptor(opt)});
  }
}

 具体使用:

  import OtherServer from "../../service/other.server";
  const otherServer = new OtherServer();

   _sendBaseLinksServer(){
        otherServer.sendBaseLinksServer({
          resetInterceptor:(config)=>{//不需要loading动画},
          onSuccess: (res) => {          
            sessionStorage.setItem('BaseLinks',JSON.stringify(res))
          },
          onFailed: (res) => {}
        })
      }

 

 

你可能感兴趣的:(vue)