bug
jiangping
2023-11-07 64b432916af9c9218ab3f3eca614e26c542142ae
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
import axios from 'axios';
import { Toast } from 'vant';
import router from "@/router";
 
// 创建一个 axios 实例
const service = axios.create({
    baseURL: process.env.VUE_APP_API_PREFIX,
    timeout: 50000,
    withCredentials: true,
    headers: { 'Content-Type': 'application/json' }
})
 
let loading: any;   // 控制加载动画
let interfaces: Array<string> = ['ext/routeCardExt/getListByWorkOrderId']   // 不需要错误提示的接口数组
 
// 添加请求拦截器
service.interceptors.request.use(
    (config) => {
        if (config.url?.indexOf('/lingyang/login') == -1 && config.url?.indexOf('/edgp/loginDemo') == -1 && config.url?.indexOf('/lingyang/loginDemo') == -1 &&config.url?.indexOf('/edgp/login') == -1) {
            loading = Toast.loading({ message: '加载中...', forbidClick: true, duration: 0 });
        }
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
)
 
// 添加响应拦截器
service.interceptors.response.use(
    (response) => {
        if (response.config.url?.indexOf('/lingyang/login') == -1 && response.config.url?.indexOf('/edgp/loginDemo') == -1 && response.config.url?.indexOf('/lingyang/loginDemo') == -1 && response.config.url?.indexOf('/edgp/login') == -1) {
            loading.clear();
        }
        if (response.data.code === 401) {     // 处理登录过期
            Toast.fail({ message: '登录过期,准备自动重新登录', duration: 2000, forbidClick: true })
            setTimeout(() => {
                router.push({ name: 'logInAgain' })
            }, 2000)
            return
        }
        // @ts-ignore
        if (response.data.code !== 200 && !interfaces.includes(response.config.url)) {     // 请求报错
            Toast.fail({ message: response.data.message, duration: 2000 })
        }
        return response.data || false;
    },
    (error) => {
        loading.clear();
        let code: number;
        if (error.code === "ECONNABORTED") {
            code = 999
        } else {
            code = error.response.status
        }
        switch (code) {
            case 404:
                Toast.fail({ message: '请求资源不存在', duration: 2000 })
                break;
            case 500:
                Toast.fail({ message: '服务器资源错误', duration: 2000 })
                break;
            case 999:
                Toast.fail({ message: '请求超时', duration: 2000 })
                break;
        }
        return Promise.reject(error);
    }
)
 
export default service;