1
lzhe
2024-05-13 f5edc2904945f37b164a7874d502cf002fae024e
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
import axios from 'axios';
import { ElNotification, ElMessageBox, ElMessage } from 'element-plus';
import sysConfig from "@/config";
import tool from '@/utils/tool';
import router from '@/router';
 
axios.defaults.baseURL = ''
 
axios.defaults.timeout = sysConfig.TIMEOUT
 
// HTTP request 拦截器
axios.interceptors.request.use(
    (config) => {
        let token = tool.cookie.get("TOKEN");
        config.headers['Authorization'] = 'Basic c2FiZXI6c2FiZXJfc2VjcmV0'
        if (token) {
            config.headers[sysConfig.TOKEN_NAME] = sysConfig.TOKEN_PREFIX + token
        }
        if (!sysConfig.REQUEST_CACHE && config.method == 'get') {
            config.params = config.params || {};
            // config.params['_'] = new Date().getTime();
        }
        Object.assign(config.headers, sysConfig.HEADERS)
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);
 
//FIX 多个API同时401时疯狂弹窗BUG
let MessageBox_401_show = false
 
// HTTP response 拦截器
axios.interceptors.response.use(
    (response) => {
        if (response.data.code && response.data.code !== 200) {
            // ElMessage({
            //     message: response.data.msg,
            //     type: 'warning',
            // })
            // return new Error()
            // return new Error();
        }
        return response;
    },
    (error) => {
        if (error.response) {
            if (error.response.status == 404) {
                ElNotification.error({
                    title: '请求错误',
                    message: "Status:404,正在请求不存在的服务器记录!"
                });
            } else if (error.response.status == 500) {
                ElNotification.error({
                    title: '请求错误',
                    message: error.response.data.message || "Status:500,服务器发生错误!"
                });
            } else if (error.response.status == 401) {
                if (!MessageBox_401_show) {
                    MessageBox_401_show = true
                    ElMessageBox.confirm('当前用户已被登出或无权限访问当前资源,请尝试重新登录后再操作。', '无权限访问', {
                        type: 'error',
                        closeOnClickModal: false,
                        center: true,
                        confirmButtonText: '重新登录',
                        beforeClose: (action, instance, done) => {
                            MessageBox_401_show = false
                            done()
                        }
                    }).then(() => {
                        router.replace({ path: '/login' });
                    }).catch(() => { })
                }
            } else {
                // ElNotification.error({
                //     title: '请求错误',
                //     message: error.message || `Status:${error.response.status},未知错误!`
                // });
            }
        } else {
            ElNotification.error({
                title: '请求错误',
                message: "请求服务器无响应!"
            });
        }
 
        return Promise.reject(error.response);
    }
);
function qsStringify(obj) {
    return Object.keys(obj)
        .map(key => {
            if (Array.isArray(obj[key])) {
                return obj[key]
                    .map(arrayValue => `${encodeURIComponent(key)}=${encodeURIComponent(arrayValue)}`)
                    .join('&');
            }
            return `${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`;
        })
        .join('&');
}
 
var http = {
 
    /** get 请求
     * @param  {string} url 接口地址
     * @param  {object} params 请求参数
     * @param  {object} config 参数
     */
    get: function (url, params = {}, config = {}) {
        return new Promise((resolve, reject) => {
            axios({
                method: 'get',
                url: url,
                params: params,
                ...config
            }).then((response) => {
                resolve(response.data);
            }).catch((error) => {
                reject(error);
            })
        })
    },
 
    /** post 请求 request payload
     * @param  {string} url 接口地址
     * @param  {object} data 请求参数
     * @param  {object} config 参数
     */
    post: function (url, data = {}, config = {}) {
        return new Promise((resolve, reject) => {
            axios({
                method: 'post',
                url: url,
                data: data,
                ...config
            }).then((response) => {
                resolve(response.data);
            }).catch((error) => {
                if (error?.status == 400) {
                    ElMessage({
                        message: error.data.msg,
                        type: 'warning',
                    })
                } else {
                    reject(error);
                }
            })
        })
    },
    /** post 请求 query string parameters
     * @param  {string} url 接口地址
     * @param  {object} data 请求参数
     * @param  {object} config 参数
     */
    postJ: function (url, data = {}, config = {}) {
        return new Promise((resolve, reject) => {
            console.log(qsStringify(data))
            axios({
                method: 'post',
                url: url,
                headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' },
                data: qsStringify(data),
                ...config
            }).then((response) => {
                resolve(response.data);
            }).catch((error) => {
                reject(error);
            })
        })
    },
    /** put 请求
     * @param  {string} url 接口地址
     * @param  {object} data 请求参数
     * @param  {object} config 参数
     */
    put: function (url, data = {}, config = {}) {
        return new Promise((resolve, reject) => {
            axios({
                method: 'put',
                url: url,
                data: data,
                ...config
            }).then((response) => {
                resolve(response.data);
            }).catch((error) => {
                reject(error);
            })
        })
    },
 
    /** patch 请求
     * @param  {string} url 接口地址
     * @param  {object} data 请求参数
     * @param  {object} config 参数
     */
    patch: function (url, data = {}, config = {}) {
        return new Promise((resolve, reject) => {
            axios({
                method: 'patch',
                url: url,
                data: data,
                ...config
            }).then((response) => {
                resolve(response.data);
            }).catch((error) => {
                reject(error);
            })
        })
    },
 
    /** delete 请求
     * @param  {string} url 接口地址
     * @param  {object} data 请求参数
     * @param  {object} config 参数
     */
    delete: function (url, data = {}, config = {}) {
        return new Promise((resolve, reject) => {
            axios({
                method: 'delete',
                url: url,
                data: data,
                ...config
            }).then((response) => {
                resolve(response.data);
            }).catch((error) => {
                if (error.status == 400) {
                    ElMessage({
                        message: error.data.msg,
                        type: 'warning',
                    })
                } else {
                    reject(error);
                }
            })
        })
    },
 
    /** jsonp 请求
     * @param  {string} url 接口地址
     * @param  {string} name JSONP回调函数名称
     */
    jsonp: function (url, name = 'jsonp') {
        return new Promise((resolve) => {
            var script = document.createElement('script')
            var _id = `jsonp${Math.ceil(Math.random() * 1000000)}`
            script.id = _id
            script.type = 'text/javascript'
            script.src = url
            window[name] = (response) => {
                resolve(response)
                document.getElementsByTagName('head')[0].removeChild(script)
                try {
                    delete window[name];
                } catch (e) {
                    window[name] = undefined;
                }
            }
            document.getElementsByTagName('head')[0].appendChild(script)
        })
    }
}
 
export default http;