vue axios封装 fetch.js

import router from "@/router";
import store from "@/store";
import axios from "axios";
import {
  Message,
  Loading
} from "element-ui";
let service = axios.create({
  timeout: 60 * 1000 * 10
});
let loadingInstance;
//请求拦截器
service.interceptors.request.use(
  config => {
    loadingInstance = Loading.service({
      lock: true,
      text: 'Loading',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    });
    config.cancelToken = store.state.axiosSource.token;
    console.log(config)
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);
//响应拦截器
service.interceptors.response.use(
  response => {
    loadingInstance.close();
    if (response.data.code == 800) {
      store.commit("setUser", null);
      store.state.axiosSource.cancel();
      if (router.currentRoute.name != "login") {
        router.push({
          name: "login",
          params: {
            reLogin: true
          }
        });
      }
    } else if (response.data.code == 200 || !response.data.code) {
        return Promise.resolve(response);
    } else {
      Message({
        message: response.data.msg,
        type: "warning"
      });
      return Promise.reject(response);
    }
  },
  error => {
    loadingInstance.close();
    if (axios.isCancel(error)) {
      return new Promise(() => {});
    }
    if (error.response) {
      switch (error.response.status) {
        case 400:
          error.message = "请求错误";
          break;
        case 401:
          error.message = "未授权,请登录";
          break;
        case 403:
          error.message = "拒绝访问";
          break;
        case 404:
          error.message = `请求地址出错: ${error.response.config.url}`;
          break;
        case 408:
          error.message = "请求超时";
          break;
        case 500:
          error.message = "服务器内部错误";
          break;
        case 501:
          error.message = "服务未实现";
          break;
        case 502:
          error.message = "网关错误";
          break;
        case 503:
          error.message = "服务不可用";
          break;
        case 504:
          error.message = "服务未启动";
          break;
        case 505:
          error.message = "HTTP版本不受支持";
          break;
        case 602:
          error.message = "当前时间不允许上报";
        break;
        default:
          error.message = "服务超时";
      }
    } else {
      error.message = "请检查网络是否通畅";
    }
    Message.error(error.message);
    return Promise.reject(error);
  }
);
export default service;

  

上一篇:Sec-Fetch-*请求头,了解下?


下一篇:MySQL_fetch_array 和 MySQL_fetch_object 的区别是 什么?