request.vue

/*
 * @Description: Please set Description
 * @Author: duanjiefei
 * @Date: 2019-09-03 19:00:11
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2019-11-11 18:30:46
 */
import axios from "axios";
import router from "../router/index";
import { Message, Loading } from "element-ui";
import store from "../store";
import { getToken } from "@/utils/auth";
import qs from "qs";

// axios 实例构建
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // api 的 base_url 接口请求的基路径
  timeout: 30000 // 请求超时时间
});

// 请求拦截
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers["X-Token"] = getToken(); // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    return config;
  },
  error => {
    // Do something with request error
    return Promise.reject(error);
  }
);

// 响应拦截
service.interceptors.response.use(
  response => {
    let data;
    // IE9
    if (response.data === undefined) {
      data = response.request.responseText;
    } else {
      data = response.data;
    }
    if (data.status === "error") {
      Message.error(data.msg);
      return data;
    } else if (data.status === "unlogin") {
      router.push({
        path: "/login"
      });
    } else if (data.status === "unauthorized") {
      router.push({
        path: "/401"
      });
    } else if (data.status === "success") {
      return data;
    } else if (data.indexOf("该用户已在其他地方登录") > 0) {
      Message.error("该用户已在其他地方登录");
      router.push({
        path: "/login"
      });
    }
  },
  err => {
    if (err.response && err.response.status) {
      switch (err.response.status) {
        case 400:
          err.message = "请求错误";
          break;
        case 401:
          err.message = "未授权,请登录";
          break;
        case 403:
          err.message = "拒绝访问";
          break;
        case 404:
          err.message = `请求地址出错: ${err.response.config.url}`;
          break;
        case 408:
          err.message = "请求超时";
          Message.error(err.message);
          router.push({
            path: "/login"
          });
          break;
        case 500:
          err.message = "服务器内部错误";
          Message.error(err.message);
          router.push({
            path: "/login"
          });
          break;
        case 501:
          err.message = "服务未实现";
          break;
        case 502:
          err.message = "网关错误";
          break;
        case 503:
          err.message = "服务不可用";
          break;
        case 504:
          err.message = "网关超时";
          break;
        case 505:
          err.message = "HTTP版本不受支持";
          break;
        default:
      }
    }
    return Promise.reject(err); // 返回错误信息
  }
);

export default function(
  option,

  // api 请求额外配置
  {
    loading = false, // 请求 loading,默认不开启
    text = "Loading", // loading 提示文本
    dataType = "json" // 请求的数据格式,默认 json , 可选 formData
  } = {}
) {
  if (loading)
    var loadingInstance = Loading.service({
      lock: true,
      text,
      spinner: "el-icon-loading",
      background: "rgba(0, 0, 0, 0.7)"
    });
  // console.log('===========',dataType);
  // 发送 formData 数据格式
  if (dataType === "formData") {
    // console.log('===========',dataType);

    option.headers = {
      "Content-Type": "application/x-www-form-urlencoded" // 含文件: multipart/form-data
    };

    option.data = qs.stringify(option.data);
  }

  return new Promise((resolve, reject) => {
    service(option)
      .then(resolve)
      .catch(reject)
      .finally(() => {
        if (loading) loadingInstance.close();
      });
  });
}

你可能感兴趣的:(Vue.js)