Houjie
2025-05-21 63b2432286110be1f270672a223c8fb9ddc24233
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
import Request from '@/common/luch-request/index.js'
import {
    ACCESS_TOKEN
} from '@/common/util/constants.js'
import configService from './config.service.js'
import tip from '@/common/util/tip.js';
import store from '@/store/index.js';
 
let apiUrl = configService.apiUrl;
 
const getTokenStorage = () => {
    let token = ''
    try {
        token = uni.getStorageSync(ACCESS_TOKEN)
    } catch (e) {
        //TODO handle the exception
        console.log("getTokenStorage", token)
    }
    return token
}
 
 
 
const http = new Request()
http.setConfig((config) => {
    /* 设置全局配置 */
    config.baseUrl = apiUrl /* 根域名不同 */
    config.header = {
        ...config.header
    }
    return config
})
 
/**
 * 自定义验证器,如果返回true 则进入响应拦截器的响应成功函数(resolve),否则进入响应拦截器的响应错误函数(reject)
 * @param { Number } statusCode - 请求响应体statusCode(只读)
 * @return { Boolean } 如果为true,则 resolve, 否则 reject
 */
// 有默认,非必写
http.validateStatus = (statusCode) => {
    return statusCode === 200
}
 
http.interceptor.request((config, cancel) => {
    /* 请求之前拦截器 */
    config.header = {
        ...config.header,
        'X-Access-Token': getTokenStorage()
    }
    /*
    if (!token) { // 如果token不存在,调用cancel 会取消本次请求,但是该函数的catch() 仍会执行
      cancel('token 不存在') // 接收一个参数,会传给catch((err) => {}) err.errMsg === 'token 不存在'
    }
    */
    return config
})
 
// 必须使用异步函数,注意
http.interceptor.response(async (response) => {
    /* 请求之后拦截器 */
    // if (response.data.code !== 200) { // 服务端返回的状态码不等于200,则reject()
    //   return Promise.reject(response)
    // }
    return response
}, (response) => {
    // 请求错误做点什么
    console.log("请求错误做点什么", response);
    if (response) {
        let data = response.data
        const token = uni.getStorageSync(ACCESS_TOKEN)
        console.log("------异常响应------", token)
        console.log("------异常响应------", data.status)
        switch (data.code) {
            case 403:
                tip.error('拒绝访问');
                break
            case 500:
                if (!token || data.message === "Token失效,请重新登录") {
                    // 先提示用户
                    tip.alert('登录已过期');
 
                    // 延迟执行登出并刷新页面,避免提示被中断
                    const timeout = setTimeout(() => {
                        store.dispatch('Logout')
                            .then(() => {
                                window.location.reload();
                            })
                            .catch((error) => {
                                console.error('Logout failed:', error);
                                window.location.reload(); // 出错时也强制刷新
                            });
                    }, 1000);
                }
                break
            case 404:
                break
            case 504:
                break
            case 401:
                uni.showModal({
                    title: '提示',
                    content: '登录超时,需要重新登录!',
                    showCancel: false,
                    success: (res) => {
                        if (res.confirm) {
                            uni.reLaunch({
                                url: '/pages/login/login'
                            })
                        }
                    }
                });
                break
            default:
                tip.error({
                    duration: 0,
                    forbidClick: true,
                    message: data.message
                });
                break
        }
    }
    return response
})
 
export {
    http
}