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