提交 | 用户 | 时间
|
221c1c
|
1 |
import axios, { AxiosError, AxiosInstance, AxiosResponse, InternalAxiosRequestConfig } from 'axios' |
820397
|
2 |
|
H |
3 |
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus' |
|
4 |
import qs from 'qs' |
|
5 |
import { config } from '@/config/axios/config' |
|
6 |
import { getAccessToken, getRefreshToken, getTenantId, removeToken, setToken } from '@/utils/auth' |
|
7 |
import errorCode from './errorCode' |
|
8 |
|
|
9 |
import { resetRouter } from '@/router' |
|
10 |
import { deleteUserCache } from '@/hooks/web/useCache' |
|
11 |
|
|
12 |
const tenantEnable = import.meta.env.VITE_APP_TENANT_ENABLE |
|
13 |
const { result_code, base_url, request_timeout } = config |
|
14 |
|
|
15 |
// 需要忽略的提示。忽略后,自动 Promise.reject('error') |
|
16 |
const ignoreMsgs = [ |
|
17 |
'无效的刷新令牌', // 刷新令牌被删除时,不用提示 |
|
18 |
'刷新令牌已过期' // 使用刷新令牌,刷新获取新的访问令牌时,结果因为过期失败,此时需要忽略。否则,会导致继续 401,无法跳转到登出界面 |
|
19 |
] |
|
20 |
// 是否显示重新登录 |
|
21 |
export const isRelogin = { show: false } |
|
22 |
// Axios 无感知刷新令牌,参考 https://www.dashingdog.cn/article/11 与 https://segmentfault.com/a/1190000020210980 实现 |
|
23 |
// 请求队列 |
|
24 |
let requestList: any[] = [] |
|
25 |
// 是否正在刷新中 |
|
26 |
let isRefreshToken = false |
|
27 |
// 请求白名单,无须token的接口 |
|
28 |
const whiteList: string[] = ['/login', '/refresh-token'] |
|
29 |
|
|
30 |
// 创建axios实例 |
|
31 |
const service: AxiosInstance = axios.create({ |
|
32 |
baseURL: base_url, // api 的 base_url |
|
33 |
timeout: request_timeout, // 请求超时时间 |
221c1c
|
34 |
withCredentials: false, // 禁用 Cookie 等信息 |
H |
35 |
// 自定义参数序列化函数 |
|
36 |
paramsSerializer: (params) => { |
|
37 |
return qs.stringify(params, { allowDots: true }) |
|
38 |
} |
820397
|
39 |
}) |
H |
40 |
|
|
41 |
// request拦截器 |
|
42 |
service.interceptors.request.use( |
|
43 |
(config: InternalAxiosRequestConfig) => { |
|
44 |
// 是否需要设置 token |
|
45 |
let isToken = (config!.headers || {}).isToken === false |
|
46 |
whiteList.some((v) => { |
221c1c
|
47 |
if (config.url && config.url.indexOf(v) > -1) { |
820397
|
48 |
return (isToken = false) |
H |
49 |
} |
|
50 |
}) |
|
51 |
if (getAccessToken() && !isToken) { |
221c1c
|
52 |
config.headers.Authorization = 'Bearer ' + getAccessToken() // 让每个请求携带自定义token |
820397
|
53 |
} |
H |
54 |
// 设置租户 |
|
55 |
if (tenantEnable && tenantEnable === 'true') { |
|
56 |
const tenantId = getTenantId() |
221c1c
|
57 |
if (tenantId) config.headers['tenant-id'] = tenantId |
820397
|
58 |
} |
221c1c
|
59 |
const method = config.method?.toUpperCase() |
H |
60 |
// 防止 GET 请求缓存 |
|
61 |
if (method === 'GET') { |
|
62 |
config.headers['Cache-Control'] = 'no-cache' |
|
63 |
config.headers['Pragma'] = 'no-cache' |
820397
|
64 |
} |
221c1c
|
65 |
// 自定义参数序列化函数 |
H |
66 |
else if (method === 'POST') { |
|
67 |
const contentType = config.headers['Content-Type'] || config.headers['content-type'] |
|
68 |
if (contentType === 'application/x-www-form-urlencoded') { |
|
69 |
if (config.data && typeof config.data !== 'string') { |
|
70 |
config.data = qs.stringify(config.data) |
|
71 |
} |
820397
|
72 |
} |
H |
73 |
} |
|
74 |
return config |
|
75 |
}, |
|
76 |
(error: AxiosError) => { |
|
77 |
// Do something with request error |
|
78 |
console.log(error) // for debug |
|
79 |
return Promise.reject(error) |
|
80 |
} |
|
81 |
) |
|
82 |
|
|
83 |
// response 拦截器 |
|
84 |
service.interceptors.response.use( |
|
85 |
async (response: AxiosResponse<any>) => { |
|
86 |
let { data } = response |
|
87 |
const config = response.config |
|
88 |
if (!data) { |
|
89 |
// 返回“[HTTP]请求没有返回值”; |
|
90 |
throw new Error() |
|
91 |
} |
|
92 |
const { t } = useI18n() |
|
93 |
// 未设置状态码则默认成功状态 |
|
94 |
// 二进制数据则直接返回,例如说 Excel 导出 |
|
95 |
if ( |
|
96 |
response.request.responseType === 'blob' || |
|
97 |
response.request.responseType === 'arraybuffer' |
|
98 |
) { |
|
99 |
// 注意:如果导出的响应为 json,说明可能失败了,不直接返回进行下载 |
|
100 |
if (response.data.type !== 'application/json') { |
|
101 |
return response.data |
|
102 |
} |
|
103 |
data = await new Response(response.data).json() |
|
104 |
} |
|
105 |
const code = data.code || result_code |
|
106 |
// 获取错误信息 |
|
107 |
const msg = data.msg || errorCode[code] || errorCode['default'] |
|
108 |
if (ignoreMsgs.indexOf(msg) !== -1) { |
|
109 |
// 如果是忽略的错误码,直接返回 msg 异常 |
|
110 |
return Promise.reject(msg) |
|
111 |
} else if (code === 401) { |
|
112 |
// 如果未认证,并且未进行刷新令牌,说明可能是访问令牌过期了 |
|
113 |
if (!isRefreshToken) { |
|
114 |
isRefreshToken = true |
|
115 |
// 1. 如果获取不到刷新令牌,则只能执行登出操作 |
|
116 |
if (!getRefreshToken()) { |
|
117 |
return handleAuthorized() |
|
118 |
} |
|
119 |
// 2. 进行刷新访问令牌 |
|
120 |
try { |
|
121 |
const refreshTokenRes = await refreshToken() |
|
122 |
// 2.1 刷新成功,则回放队列的请求 + 当前请求 |
|
123 |
setToken((await refreshTokenRes).data.data) |
|
124 |
config.headers!.Authorization = 'Bearer ' + getAccessToken() |
|
125 |
requestList.forEach((cb: any) => { |
|
126 |
cb() |
|
127 |
}) |
|
128 |
requestList = [] |
|
129 |
return service(config) |
|
130 |
} catch (e) { |
|
131 |
// 为什么需要 catch 异常呢?刷新失败时,请求因为 Promise.reject 触发异常。 |
|
132 |
// 2.2 刷新失败,只回放队列的请求 |
|
133 |
requestList.forEach((cb: any) => { |
|
134 |
cb() |
|
135 |
}) |
|
136 |
// 提示是否要登出。即不回放当前请求!不然会形成递归 |
|
137 |
return handleAuthorized() |
|
138 |
} finally { |
|
139 |
requestList = [] |
|
140 |
isRefreshToken = false |
|
141 |
} |
|
142 |
} else { |
|
143 |
// 添加到队列,等待刷新获取到新的令牌 |
|
144 |
return new Promise((resolve) => { |
|
145 |
requestList.push(() => { |
|
146 |
config.headers!.Authorization = 'Bearer ' + getAccessToken() // 让每个请求携带自定义token 请根据实际情况自行修改 |
|
147 |
resolve(service(config)) |
|
148 |
}) |
|
149 |
}) |
|
150 |
} |
|
151 |
} else if (code === 500) { |
|
152 |
ElMessage.error(t('sys.api.errMsg500')) |
|
153 |
return Promise.reject(new Error(msg)) |
|
154 |
} else if (code === 901) { |
|
155 |
ElMessage.error({ |
|
156 |
offset: 300, |
|
157 |
dangerouslyUseHTMLString: true, |
|
158 |
message: |
|
159 |
'<div>' + |
|
160 |
t('sys.api.errMsg901') + |
|
161 |
'</div>' + |
|
162 |
'<div> </div>' + |
221c1c
|
163 |
'<div>参考 https://doc.iailab.cn/ 教程</div>' + |
820397
|
164 |
'<div> </div>' + |
H |
165 |
'<div>5 分钟搭建本地环境</div>' |
|
166 |
}) |
|
167 |
return Promise.reject(new Error(msg)) |
|
168 |
} else if (code !== 200) { |
|
169 |
if (msg === '无效的刷新令牌') { |
|
170 |
// hard coding:忽略这个提示,直接登出 |
|
171 |
console.log(msg) |
|
172 |
return handleAuthorized() |
|
173 |
} else { |
|
174 |
ElNotification.error({ title: msg }) |
|
175 |
} |
|
176 |
return Promise.reject('error') |
|
177 |
} else { |
|
178 |
return data |
|
179 |
} |
|
180 |
}, |
|
181 |
(error: AxiosError) => { |
|
182 |
console.log('err' + error) // for debug |
|
183 |
let { message } = error |
|
184 |
const { t } = useI18n() |
|
185 |
if (message === 'Network Error') { |
|
186 |
message = t('sys.api.errorMessage') |
|
187 |
} else if (message.includes('timeout')) { |
|
188 |
message = t('sys.api.apiTimeoutMessage') |
|
189 |
} else if (message.includes('Request failed with status code')) { |
|
190 |
message = t('sys.api.apiRequestFailed') + message.substr(message.length - 3) |
|
191 |
} |
|
192 |
ElMessage.error(message) |
|
193 |
return Promise.reject(error) |
|
194 |
} |
|
195 |
) |
|
196 |
|
|
197 |
const refreshToken = async () => { |
|
198 |
axios.defaults.headers.common['tenant-id'] = getTenantId() |
|
199 |
return await axios.post(base_url + '/system/auth/refresh-token?refreshToken=' + getRefreshToken()) |
|
200 |
} |
|
201 |
const handleAuthorized = () => { |
|
202 |
const { t } = useI18n() |
|
203 |
if (!isRelogin.show) { |
|
204 |
isRelogin.show = true |
|
205 |
ElMessageBox.confirm(t('sys.api.timeoutMessage'), t('common.confirmTitle'), { |
|
206 |
showCancelButton: false, |
|
207 |
closeOnClickModal: false, |
|
208 |
showClose: false, |
221c1c
|
209 |
closeOnPressEscape: false, |
820397
|
210 |
confirmButtonText: t('login.relogin'), |
H |
211 |
type: 'warning' |
|
212 |
}).then(() => { |
|
213 |
resetRouter() // 重置静态路由表 |
|
214 |
deleteUserCache() // 删除用户缓存 |
|
215 |
removeToken() |
|
216 |
isRelogin.show = false |
|
217 |
// 干掉token后再走一次路由让它过router.beforeEach的校验 |
|
218 |
window.location.href = window.location.href |
|
219 |
}) |
|
220 |
} |
|
221 |
return Promise.reject(t('sys.api.timeoutMessage')) |
|
222 |
} |
|
223 |
export { service } |