refactor(axios): 优化 Axios 配置与响应处理逻辑
- 统一导入语句格式,去除多余空格 - 优化对象解构赋值写法 - 修复授权头设置中的语法问题 - 完善 QS 参数序列化配置 - 增加对 504 状态码的处理 - 优化错误消息提示逻辑与界面展示 - 调整更多错误详情查看按钮样式 - 更新网络错误与超时提示文本 - 修复登出处理中的国际化调用 - 清理缓存并重置路由逻辑调整 - 调整错误弹窗最大宽度样式 - 导出 service 实例供外部使用
This commit is contained in:
@@ -6,17 +6,17 @@ import axios, {
|
||||
InternalAxiosRequestConfig
|
||||
} from 'axios'
|
||||
|
||||
import { ElMessage, ElMessageBox, ElNotification, ElButton } from 'element-plus'
|
||||
import {ElMessage, ElMessageBox, ElNotification, ElButton} from 'element-plus'
|
||||
import qs from 'qs'
|
||||
import { config, specificApiTimeoutObj } from '@/config/axios/config'
|
||||
import { getAccessToken, getRefreshToken, getTenantId, removeToken, setToken } from '@/utils/auth'
|
||||
import {config, specificApiTimeoutObj} from '@/config/axios/config'
|
||||
import {getAccessToken, getRefreshToken, getTenantId, removeToken, setToken} from '@/utils/auth'
|
||||
import errorCode from './errorCode'
|
||||
|
||||
import { resetRouter } from '@/router'
|
||||
import { useCache } from '@/hooks/web/useCache'
|
||||
import {resetRouter} from '@/router'
|
||||
import {useCache} from '@/hooks/web/useCache'
|
||||
|
||||
const tenantEnable = import.meta.env.VITE_APP_TENANT_ENABLE
|
||||
const { result_code, base_url, request_timeout } = config
|
||||
const {result_code, base_url, request_timeout} = config
|
||||
|
||||
// 需要忽略的提示。忽略后,自动 Promise.reject('error')
|
||||
const ignoreMsgs = [
|
||||
@@ -24,7 +24,7 @@ const ignoreMsgs = [
|
||||
'刷新令牌已过期' // 使用刷新令牌,刷新获取新的访问令牌时,结果因为过期失败,此时需要忽略。否则,会导致继续 401,无法跳转到登出界面
|
||||
]
|
||||
// 是否显示重新登录
|
||||
export const isRelogin = { show: false }
|
||||
export const isRelogin = {show: false}
|
||||
// Axios 无感知刷新令牌,参考 https://www.dashingdog.cn/article/11 与 https://segmentfault.com/a/1190000020210980 实现
|
||||
// 请求队列
|
||||
let requestList: any[] = []
|
||||
@@ -51,7 +51,7 @@ service.interceptors.request.use(
|
||||
}
|
||||
})
|
||||
if (getAccessToken() && !isToken) {
|
||||
; (config as Recordable).headers.Authorization = 'Bearer ' + getAccessToken() // 让每个请求携带自定义token
|
||||
;(config as Recordable).headers.Authorization = 'Bearer ' + getAccessToken() // 让每个请求携带自定义token
|
||||
}
|
||||
// 设置租户
|
||||
if (tenantEnable && tenantEnable === 'true') {
|
||||
@@ -74,7 +74,7 @@ service.interceptors.request.use(
|
||||
// get参数编码
|
||||
if (config.method?.toUpperCase() === 'GET' && params) {
|
||||
config.params = {}
|
||||
const paramsStr = qs.stringify(params, { allowDots: true })
|
||||
const paramsStr = qs.stringify(params, {allowDots: true})
|
||||
if (paramsStr) {
|
||||
config.url = config.url + '?' + paramsStr
|
||||
}
|
||||
@@ -91,13 +91,13 @@ service.interceptors.request.use(
|
||||
// response 拦截器
|
||||
service.interceptors.response.use(
|
||||
async (response: AxiosResponse<any>) => {
|
||||
let { data } = response
|
||||
let {data} = response
|
||||
const config = response.config
|
||||
if (!data) {
|
||||
// 返回“[HTTP]请求没有返回值”;
|
||||
throw new Error()
|
||||
}
|
||||
const { t } = useI18n()
|
||||
const {t} = useI18n()
|
||||
// 未设置状态码则默认成功状态
|
||||
// 二进制数据则直接返回,例如说 Excel 导出
|
||||
if (
|
||||
@@ -159,6 +159,8 @@ service.interceptors.response.use(
|
||||
} else if (code === 500) {
|
||||
ElMessage.error(t('sys.api.errMsg500'))
|
||||
return Promise.reject(new Error(msg))
|
||||
} else if (code === 504) {
|
||||
return Promise.reject(new Error(msg))
|
||||
} else if (code === 901) {
|
||||
ElMessage.error({
|
||||
offset: 300,
|
||||
@@ -174,10 +176,10 @@ service.interceptors.response.use(
|
||||
title: msg,
|
||||
dangerouslyUseHTMLString: true,
|
||||
message: h(ElButton, {
|
||||
link: true,
|
||||
type: 'primary',
|
||||
onClick: () => handleMoreError(msg, data.data)
|
||||
},
|
||||
link: true,
|
||||
type: 'primary',
|
||||
onClick: () => handleMoreError(msg, data.data)
|
||||
},
|
||||
'点击查看具体原因'
|
||||
)
|
||||
})
|
||||
@@ -186,7 +188,7 @@ service.interceptors.response.use(
|
||||
// hard coding:忽略这个提示,直接登出
|
||||
console.log(msg)
|
||||
} else {
|
||||
ElNotification.error({ title: msg })
|
||||
ElNotification.error({title: msg})
|
||||
}
|
||||
return Promise.reject('error')
|
||||
} else {
|
||||
@@ -195,8 +197,8 @@ service.interceptors.response.use(
|
||||
},
|
||||
(error: AxiosError) => {
|
||||
console.log('err' + error) // for debug
|
||||
let { message } = error
|
||||
const { t } = useI18n()
|
||||
let {message} = error
|
||||
const {t} = useI18n()
|
||||
if (message === 'Network Error') {
|
||||
message = t('sys.api.errorMessage')
|
||||
} else if (message.includes('timeout')) {
|
||||
@@ -214,7 +216,7 @@ const refreshToken = async () => {
|
||||
return await axios.post('/system/auth/refresh-token?refreshToken=' + getRefreshToken())
|
||||
}
|
||||
const handleAuthorized = () => {
|
||||
const { t } = useI18n()
|
||||
const {t} = useI18n()
|
||||
if (!isRelogin.show) {
|
||||
// 如果已经到重新登录页面则不进行弹窗提示
|
||||
if (window.location.href.includes('login?redirect=')) {
|
||||
@@ -228,7 +230,7 @@ const handleAuthorized = () => {
|
||||
confirmButtonText: t('login.relogin'),
|
||||
type: 'warning'
|
||||
}).then(() => {
|
||||
const { wsCache } = useCache()
|
||||
const {wsCache} = useCache()
|
||||
resetRouter() // 重置静态路由表
|
||||
wsCache.clear()
|
||||
removeToken()
|
||||
@@ -242,7 +244,7 @@ const handleAuthorized = () => {
|
||||
const handleMoreError = (title, message) => {
|
||||
ElMessageBox.alert(`<div style="white-space: break-spaces;">${message}</div>`, title, {
|
||||
dangerouslyUseHTMLString: true,
|
||||
customStyle: { maxWidth: '40%' }
|
||||
customStyle: {maxWidth: '40%'}
|
||||
})
|
||||
}
|
||||
export { service }
|
||||
export {service}
|
||||
|
||||
Reference in New Issue
Block a user