吉安感知网项目-前端
shuishen
5 days ago 6e88705bd5b443a259b24c17c8a299765d059d96
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
import axios from 'axios'
import store from '@/store/'
import { serialize, logOutFun } from '@/utils/util'
import { getToken, removeToken, removeRefreshToken } from '@/utils/auth'
 
import { ElMessage } from 'element-plus'
let isErrorShown = false
let _retry = false
// 全局未授权错误提示状态,只提示一次
const { VITE_APP_API_XT, VITE_APP_ENV, VITE_APP_URL_XT } = import.meta.env
const serviceXT = axios.create({
    timeout: 600000,
    baseURL: VITE_APP_ENV === 'development' ? VITE_APP_API_XT : VITE_APP_URL_XT,
    //跨域请求,允许保存cookie
    withCredentials: false,
})
 
 
//http request拦截
serviceXT.interceptors.request.use(
    config => {
        const authorization = config.authorization === false
        const xtToken = store.state.user.xtToken
        if (xtToken && !authorization) {
            config.headers['Authorization'] = xtToken
        }
        const meta = config.meta || {}
 
        //headers中配置text请求
        if (config.text === true) {
            config.headers['Content-Type'] = 'text/plain'
        }
        //headers中配置serialize为true开启序列化
        if (config.method === 'post' && meta.isSerialize === true) {
            config.data = serialize(config.data)
        }
        return config
    },
    error => {
        return Promise.reject(error)
    }
)
//http response拦截
serviceXT.interceptors.response.use(
    res => {
        const status = res?.data?.code || res?.data?.error_code || res?.status
        const message = res?.data?.msg || res?.data?.message || '系统错误'
 
        // 如果是401并且已经重试过,直接跳转到登录页面
        if ((status === 401) && !_retry) {
            _retry = true
            // 首次报错时提示
            if (!isErrorShown) {
                isErrorShown = true
                ElMessage.error('用户令牌过期,请重新登录')
            }
            // 清除token信息
            removeToken()
            removeRefreshToken()
            // 重定向到登录页
            logOutFun().then(() => {
                isErrorShown = false
                _retry = false
            })
            return Promise.reject(new Error(message))
        }
 
        // 如果请求为非200默认统一处理
        if (status !== 200 && status !== 0) {
            ElMessage({ message: message, type: 'error', })
            return Promise.reject(new Error(message))
        }
        return res
    },
    error => {
        return Promise.reject(new Error(error))
    }
)
export default serviceXT