Blame view

src/utils/request.js 2.74 KB
任超 committed
1
/*
2
 * @Description: 此文件主要创建 axios 实例,然后添加请求拦截器和响应拦截器
任超 committed
3
 * @Autor: renchao
4
 * @LastEditTime: 2023-03-29 10:14:34
任超 committed
5
 */
6
import Vue from 'vue'
7 8 9 10
import axios from "axios";
import { Message } from "element-ui";
import { endLoadingSubCount } from "./requestLoading";
import router from "../router";
任超 committed
11 12
// create an axios instance
const service = axios.create({
13 14 15 16 17
  baseURL: process.env.VUE_APP_BASE_API,
  withCredentials: true, //是否允许跨域
  headers: {
    "Content-Type": "application/json; charset=utf-8",
  },
18

19 20
  timeout: 15000,
});
任超 committed
21 22 23

// request interceptor
service.interceptors.request.use(
24 25
  (config) => {
    //调用登录接口时无token,也不需要传token,其他接口都传入token
yangwei committed
26
    config.headers.Authorization = localStorage.getItem("token") || "";
27 28 29 30 31 32 33 34
    config.headers.Accept = "application/json";
    return config;
  },
  (error) => {
    Message.error("请求超时!");
    return Promise.reject(error);
  }
);
任超 committed
35

yangwei committed
36
window.tokenValid = true
任超 committed
37 38
// response interceptor
service.interceptors.response.use(
39 40 41 42 43 44 45 46
  (response) => {
    /**
     *  对响应数据判断:
     *  如果成功返回数据,就通过return把数据返出去
     *  如果请求不成功,就在拦截器这里统一处理(组件的代码就不用关注错误的情况了)
     */
    if (response.status == 200) {
      return response.data;
任超 committed
47
    } else {
48 49 50 51 52 53
      // 对响应错误做点什么
      Message({
        message: "请求失败",
        type: "error",
        duration: 5 * 1000,
      });
任超 committed
54
    }
55 56 57 58 59 60 61 62 63
    return response;
  },
  (error) => {
    handleErrorData(error.response.status);
    endLoadingSubCount();
    return Promise.reject(error);
  }
);
//对错误信息的处理函数
任超 committed
64
function handleErrorData (status) {
65
  switch (status) {
yangwei committed
66 67 68 69 70 71
    case 401:
      // 多个请求不重复提示错误信息
      if (window.tokenValid) {
        window.tokenValid = false;
        Message.error("由于长时间未操作,请重新登录!");
        localStorage.removeItem("token");
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
        let code = Vue.prototype.BASE_API.CODE
        if (code == 'BDCSBPT') {
          router.replace({
            path: "/sb",
            query: {
              redirect: router.history.current.fullPath,
            },
          });
        } else {
          router.replace({
            path: "/jg",
            query: {
              redirect: router.history.current.fullPath,
            },
          });
        }
        
yangwei committed
89 90
      }
      break;
91 92 93 94 95 96 97 98 99 100 101 102 103
    case 403:
      Message.error("拒绝访问");
      break;
    case 404:
      Message.error("很抱歉,资源未找到!");
      break;
    case 500:
      Message.error("服务器错误!");
      break;
    default:
      Message.error("服务正在联调中,请稍后!");
      break;
  }
任超 committed
104
}
105
export default service;