Files
pqs-9100_client/frontend/src/api/index.ts

173 lines
6.6 KiB
TypeScript
Raw Normal View History

2025-01-22 12:09:32 +08:00
import { ElMessage, ElTreeSelect } from 'element-plus';
2024-11-15 13:47:07 +08:00
import axios, { AxiosInstance, AxiosError, AxiosRequestConfig, InternalAxiosRequestConfig, AxiosResponse } from 'axios'
import { showFullScreenLoading, tryHideFullScreenLoading } from '@/components/Loading/fullScreen'
import { LOGIN_URL } from '@/config'
import { ElMessage } from 'element-plus'
import { ResultData } from '@/api/interface'
import { ResultEnum } from '@/enums/httpEnum'
import { checkStatus } from './helper/checkStatus'
import { useUserStore } from '@/stores/modules/user'
import router from '@/routers'
2025-02-07 14:28:15 +08:00
import {refreshToken} from '@/api/user/login'
2024-08-22 11:27:06 +08:00
export interface CustomAxiosRequestConfig extends InternalAxiosRequestConfig {
loading?: boolean;
}
const config = {
// 默认地址请求地址,可在 .env.** 文件中修改
baseURL: import.meta.env.VITE_API_URL as string,
// 设置超时时间
timeout: ResultEnum.TIMEOUT as number,
// 跨域时候允许携带凭证
2024-10-10 11:29:48 +08:00
withCredentials: true,
// post请求指定数据类型以及编码
2024-11-15 13:47:07 +08:00
headers: { 'Content-Type': 'application/json;charset=utf-8' },
}
2024-08-22 11:27:06 +08:00
class RequestHttp {
2024-11-15 13:47:07 +08:00
service: AxiosInstance
2024-08-22 11:27:06 +08:00
public constructor(config: AxiosRequestConfig) {
2024-10-10 11:29:48 +08:00
// 创建实例
2024-11-15 13:47:07 +08:00
this.service = axios.create(config)
2024-08-22 11:27:06 +08:00
/**
* @description
* -> [] ->
* token校验(JWT) : token, vuex/pinia/
*/
this.service.interceptors.request.use(
(config: CustomAxiosRequestConfig) => {
2024-11-15 13:47:07 +08:00
const userStore = useUserStore()
2024-08-22 11:27:06 +08:00
// 当前请求不需要显示 loading在 api 服务中通过指定的第三个参数: { loading: false } 来控制
2024-11-15 13:47:07 +08:00
config.loading ?? (config.loading = true)
config.loading && showFullScreenLoading()
if (config.headers && typeof config.headers.set === 'function') {
2025-02-07 10:39:30 +08:00
config.headers.set('Authorization', 'Bearer ' + userStore.accessToken)
config.headers.set('Is-Refresh-Token', userStore.isRefreshToken+"")
2024-08-22 11:27:06 +08:00
}
2024-11-15 13:47:07 +08:00
return config
2024-08-22 11:27:06 +08:00
},
(error: AxiosError) => {
2024-11-15 13:47:07 +08:00
return Promise.reject(error)
},
)
2024-08-22 11:27:06 +08:00
2025-02-07 14:28:15 +08:00
let isFirst = true
2024-08-22 11:27:06 +08:00
/**
* @description
* -> [] -> JS获取到信息
*/
this.service.interceptors.response.use(
2025-02-07 14:28:15 +08:00
async (response: AxiosResponse) => {
2024-11-15 13:47:07 +08:00
const { data } = response
const userStore = useUserStore()
tryHideFullScreenLoading()
2025-02-07 14:28:15 +08:00
if(data.code === ResultEnum.ACCESSTOKEN_EXPIRED){
// 用长token去换短token
userStore.setAccessToken(userStore.refreshToken)
userStore.setIsRefreshToken(true)
2025-02-07 14:28:15 +08:00
const result = await refreshToken()
if (result) { //获取新token成功的话
// 有新的token后重新请求
userStore.setAccessToken(result.data.accessToken)
userStore.setRefreshToken(result.data.refreshToken)
2025-02-14 09:57:26 +08:00
userStore.setIsRefreshToken(false)
2025-02-07 14:28:15 +08:00
response.config.headers.Authorization = `Bearer ${result.data.accessToken}`//重新请求前需要将更新后的新token更换掉之前无效的token,不然会死循环
const resp = await this.service.request(response.config)
return resp
} else {
// 刷新失效,跳转登录页
}
}
2024-08-22 11:27:06 +08:00
// 登陆失效
if (data.code == ResultEnum.OVERDUE) {
2025-02-07 14:28:15 +08:00
console.log("登陆失效")
2025-02-07 10:39:30 +08:00
userStore.setAccessToken('')
userStore.setRefreshToken('')
2025-02-14 09:57:26 +08:00
userStore.setIsRefreshToken(false)
2025-01-16 19:45:48 +08:00
userStore.setUserInfo({ name: '' })
2024-11-15 13:47:07 +08:00
router.replace(LOGIN_URL)
2025-02-14 09:57:26 +08:00
if(isFirst){//临时处理token失效弹窗多次
2025-02-07 14:28:15 +08:00
ElMessage.error(data.message)
isFirst = false
}
2024-11-15 13:47:07 +08:00
return Promise.reject(data)
2024-08-22 11:27:06 +08:00
}
// 全局错误信息拦截(防止下载文件的时候返回数据流,没有 code 直接报错)
if (data.code && data.code !== ResultEnum.SUCCESS) {
2025-01-22 12:09:32 +08:00
if(data.message.includes('&')){
const formattedMessage = data.message.split('&').join('<br>');
ElMessage.error({ message: formattedMessage, dangerouslyUseHTMLString: true });
return Promise.reject(data)
}
2024-11-15 13:47:07 +08:00
ElMessage.error(data.message)
return Promise.reject(data)
2024-08-22 11:27:06 +08:00
}
// 成功请求(在页面上除非特殊情况,否则不用处理失败逻辑)
2024-11-15 13:47:07 +08:00
return data
2024-08-22 11:27:06 +08:00
},
async (error: AxiosError) => {
2024-11-15 13:47:07 +08:00
const { response } = error
tryHideFullScreenLoading()
2025-02-07 14:28:15 +08:00
console.log('error', error.message)
2024-08-22 11:27:06 +08:00
// 请求超时 && 网络错误单独判断,没有 response
2024-11-15 13:47:07 +08:00
if (error.message.indexOf('timeout') !== -1) ElMessage.error('请求超时!请您稍后重试')
if (error.message.indexOf('Network Error') !== -1) ElMessage.error('网络错误!请您稍后重试')
2024-08-22 11:27:06 +08:00
// 根据服务器响应的错误状态码,做不同的处理
2024-11-15 13:47:07 +08:00
if (response) checkStatus(response.status)
2024-08-22 11:27:06 +08:00
// 服务器结果都没有返回(可能服务器错误可能客户端断网),断网处理:可以跳转到断网页面
2024-11-15 13:47:07 +08:00
if (!window.navigator.onLine) router.replace('/500')
return Promise.reject(error)
},
)
2024-08-22 11:27:06 +08:00
}
/**
* @description
*/
get<T>(url: string, params?: object, _object = {}): Promise<ResultData<T>> {
2024-11-15 13:47:07 +08:00
return this.service.get(url, { params, ..._object })
2024-08-22 11:27:06 +08:00
}
2024-11-15 13:47:07 +08:00
2024-08-22 11:27:06 +08:00
post<T>(url: string, params?: object | string, _object = {}): Promise<ResultData<T>> {
2024-11-15 13:47:07 +08:00
return this.service.post(url, params, _object)
2024-08-22 11:27:06 +08:00
}
2024-11-15 13:47:07 +08:00
2024-08-22 11:27:06 +08:00
put<T>(url: string, params?: object, _object = {}): Promise<ResultData<T>> {
2024-11-15 13:47:07 +08:00
return this.service.put(url, params, _object)
2024-08-22 11:27:06 +08:00
}
2024-11-15 13:47:07 +08:00
2024-08-22 11:27:06 +08:00
delete<T>(url: string, params?: any, _object = {}): Promise<ResultData<T>> {
2024-11-15 13:47:07 +08:00
return this.service.delete(url, { params, ..._object })
2024-08-22 11:27:06 +08:00
}
2024-11-15 13:47:07 +08:00
2024-08-22 11:27:06 +08:00
download(url: string, params?: object, _object = {}): Promise<BlobPart> {
2024-11-15 13:47:07 +08:00
return this.service.post(url, params, { ..._object, responseType: 'blob' })
}
upload(url: string, params?: object, _object = {}): Promise<BlobPart> {
2025-01-16 19:45:48 +08:00
return this.service.post(url, params, {
..._object,
headers: { 'Content-Type': 'multipart/form-data' }
})
2024-08-22 11:27:06 +08:00
}
2024-11-14 11:34:25 +08:00
2025-01-16 19:45:48 +08:00
/**
* excel的上传blob类型Excel没问题时返回json特殊处理
*/
uploadExcel(url: string, params?: object, _object = {}): Promise<BlobPart> {
return this.service.post(url, params, {
..._object,
headers: { 'Content-Type': 'multipart/form-data' },
responseType: 'blob',
})
}
2024-08-22 11:27:06 +08:00
}
2024-11-15 13:47:07 +08:00
export default new RequestHttp(config)