2023西安数博会CIM演示-【前端】-Web
AdaKing88
2023-08-21 bc03b832caa49bbcd2674fe4cae3701b5059bf95
1
2
3
4
5
6
7
8
9
10
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
/*
 * @Description:
 * @Author: 王旭
 * @Date: 2022-03-03 15:10:54
 * @LastEditTime: 2023-07-17 15:23:15
 * @LastEditors: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 */
import axios from "axios";
import { Message ,Loading} from "element-ui";
import store from "@/store";
import { getToken } from "@/utils/auth";
import { tansParams, blobValidate } from "@/utils/ruoyi";
let downloadLoadingInstance;
// create an axios instance
const service = axios.create({
  // baseURL: BASE_URL, // api的base_url
  timeout: 35000, // 请求超时时间
  headers: {
    "content-type": "application/json;charset=UTF-8",
    "Cross-Origin-Opener-Policy": "same-origin",
    "Cross-Origin-Embedder-Policy": "require-corp"
  },
  // withCredentials: true,
});
 
// request interceptor
service.interceptors.request.use(
  (config) => {
    // 请求携带token
    if (store.getters.token) {
    }
    config.headers["X-Token"] = getToken();
    config.headers['Authorization'] = 'Bearer ' + getToken();
    //加载loading
    store.commit("UPDATE_API_COUNT", "add");
 
    // get请求映射params参数
    if (config.method === 'get' && config.params) {
      let url = config.url + '?' + tansParams(config.params);
      url = url.slice(0, -1);
      config.params = {};
      config.url = url;
    }
    return config;
  },
  (error) => {
    //减去loading
    store.commit("UPDATE_API_COUNT", "sub");
    console.log(error); // for debug
    return Promise.reject(error);
  }
); service.interceptors.response.use(
  (response) => {
    store.commit("UPDATE_API_COUNT", "sub");
    //console.log(response) 
    //返回因有ResponeType===Blob ,分开处理
    if (Object.prototype.toString.call(response.data).indexOf("Blob") > -1) {
      let reader = new FileReader()
      reader.onload = function (e) {
        {
          try {
            let str = this.result.toString();
            let res = JSON.parse(str);
            if (res.code !== 200) {
              Message.error(res.msg);
            }
          } catch { }
        }
      }
      reader.readAsText(response.data, "utf-8");
    } else {
      // if (response.data.code !== 200) {
      //   Message.error(response.data.msg);
      // }
    }// 报错提示
    return response.data;
  },
  (error) => {
    store.commit("UPDATE_API_COUNT", "sub");
    debugger;
    const { status, data } = error.response;
    //返回因有ResponeType===Blob ,分开处理
    if (Object.prototype.toString.call(data).indexOf("Blob") > -1) {
      let reader = new FileReader()
      reader.onload = function (e) {
        {
          let str = this.result.toString();
          let res = JSON.parse(str);
          Message({
            message: res.message,
            type: "error",
            duration: 5 * 1000,
          });
        }
      }
      reader.readAsText(data, "utf-8");
    } else {
      Message({
        message: data.message,
        type: "error",
        duration: 5 * 1000,
      });
    }
    return Promise.reject(error);
  }
);
// 通用下载方法
export function download(url, params, filename, config) {
  downloadLoadingInstance = Loading.service({ text: "正在下载数据,请稍候", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", })
  return service.post(url, params, {
    transformRequest: [(params) => { return tansParams(params) }],
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    responseType: 'blob',
    ...config
  }).then(async (data) => {
    const isBlob = blobValidate(data);
    if (isBlob) {
      const blob = new Blob([data])
      saveAs(blob, filename)
    } else {
      const resText = await data.text();
      const rspObj = JSON.parse(resText);
      const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
      Message.error(errMsg);
    }
    downloadLoadingInstance.close();
  }).catch((r) => {
    console.error(r)
    Message.error('下载文件出现错误,请联系管理员!')
    downloadLoadingInstance.close();
  })
}
 
export default service;