axios.js 1.67 KB
Newer Older
godwithdh's avatar
godwithdh committed
1 2 3

import Axios from 'axios';
import Qs from 'qs';
张锡奇's avatar
张锡奇 committed
4 5 6 7 8 9 10
import Vue from 'vue';
import  { ConfirmPlugin,ToastPlugin } from 'vux'

Vue.use(ConfirmPlugin)
let vm = new Vue()
window.d = vm;

godwithdh's avatar
godwithdh committed
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
const config = {
  baseURL: '',
  timeout: 300000, 
  withCredentials: true, //是否允许跨域
  headers: {'Content-Type': 'application/json;charset=UTF-8', 'X-Requested-With': 'XMLHttpRequest'},
  //返回数据类型
  responseType: 'json'
};
const AsInst = Axios.create(config);

// AsInst.defaults.timeout = 300000;
//请求拦截器
AsInst.interceptors.request.use((config) => {
  //若是有做鉴权token , 就给头部带上token
  // if (window.localStorage.getItem('loginToken')) {
  //   config.headers.Authorization = `${window.localStorage.getItem('loginToken')}`;
  // }
  return config;
}, (err) => {
  return Promise.reject(err);
});
//响应拦截器
AsInst.interceptors.response.use(response => {
  //检查数据是否返回NULL
  // if (response.data === null) {
  //   return Promise.reject(response);
  // }
  // //检查是否有错误
  // if(response.data.code!=0){
  //   return Promise.reject(response);
  // }
  return response;
}, (error) => {
张锡奇's avatar
张锡奇 committed
44 45 46 47 48 49 50
  if(error.response.data.hasOwnProperty('error_data')){
    vm.$vux.confirm.show({
      title:"提示",
      content:error.response.data.error_title,
      showCancelButton:false,
    })
  }
godwithdh's avatar
godwithdh committed
51 52
  // 下面是接口回调的status ,因为我做了一些错误页面,所以都会指向对应的报错页面
  if (error.response.status === 404) {
张锡奇's avatar
张锡奇 committed
53 54
      Vue.prototype.$toast('请求接口不存在!',2000)
      // Message.error('后端服务请求404错误');
godwithdh's avatar
godwithdh committed
55 56 57 58 59
  }
  //请求错误时做些事
  return Promise.reject(error);
});
export default AsInst;