index.ts 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. import axios from 'axios'
  2. import type { AxiosInstance, AxiosError, AxiosRequestConfig, InternalAxiosRequestConfig, AxiosResponse } from 'axios'
  3. import { ElMessage, ElLoading } from 'element-plus'
  4. import { ResultEnum, ResultData, ContentType } from './interface/index'
  5. import { GlobalStore } from '@/stores/index'
  6. import { useRouter } from 'vue-router'
  7. const router = useRouter()
  8. const globalStore = GlobalStore()
  9. type LoadingType = {
  10. close?: () => void
  11. }
  12. let loadingInstance: LoadingType = {}
  13. const config = {
  14. // 默认地址请求地址,可在 .env.*** 文件中修改
  15. // baseURL: import.meta.env.VITE_BZD_ERP_APP_API as string,
  16. // 设置超时时间(10s)
  17. timeout: ResultEnum.TIMEOUT as number,
  18. // 跨域时候允许携带凭证
  19. withCredentials: true,
  20. headers: {
  21. 'Content-Type': ContentType.URLENCODED
  22. }
  23. }
  24. class RequestHttp {
  25. service: AxiosInstance
  26. public constructor(config: AxiosRequestConfig) {
  27. // 实例化axios
  28. this.service = axios.create(config)
  29. /**
  30. * @description 请求拦截器
  31. * 客户端发送请求 -> [请求拦截器] -> 服务器
  32. * token校验(JWT) : 接受服务器返回的token,存储到vuex/pinia/本地储存当中
  33. */
  34. this.service.interceptors.request.use(
  35. (config: InternalAxiosRequestConfig) => {
  36. // 开始loading
  37. loadingInstance = ElLoading.service({
  38. lock: true,
  39. text: 'Loading',
  40. background: 'rgba(0, 0, 0, 0.7)'
  41. })
  42. // 加入token
  43. // if (globalStore.GET_User_tokey) {
  44. // config.headers['User_tokey'] = globalStore.GET_User_tokey
  45. // }
  46. return config
  47. },
  48. (err: any) => err
  49. )
  50. /**
  51. * @description 响应拦截器
  52. * 服务器换返回信息 -> [拦截统一处理] -> 客户端JS获取到信息
  53. */
  54. this.service.interceptors.response.use(
  55. (response: AxiosResponse) => {
  56. const { data } = response
  57. // * 在请求结束后,并关闭请求 loading
  58. loadingInstance.close && loadingInstance.close()
  59. // * 登陆失效(code == 401)
  60. if (data.code == ResultEnum.OVERDUE) {
  61. ElMessage.error(data.msg)
  62. globalStore.SET_User_Tokey('')
  63. router.replace('/login')
  64. return Promise.reject(data)
  65. }
  66. // * 全局错误信息拦截(防止下载文件得时候返回数据流,没有code,直接报错)
  67. if (data.code && data.code !== ResultEnum.SUCCESS) {
  68. ElMessage.error(data.msg)
  69. return Promise.reject(data)
  70. }
  71. // * 成功请求(在页面上除非特殊情况,否则不用在页面处理失败逻辑)
  72. return data
  73. },
  74. async (error: AxiosError) => {
  75. loadingInstance.close && loadingInstance.close()
  76. // 请求超时 && 网络错误单独判断,没有 response
  77. if (error.message.indexOf('timeout') !== -1) ElMessage.error('请求超时!请您稍后重试')
  78. if (error.message.indexOf('Network Error') !== -1) ElMessage.error('网络错误!请您稍后重试')
  79. return Promise.reject(error)
  80. }
  81. )
  82. }
  83. // * 常用请求方法封装
  84. get<T>(url: string, params?: object, _object = {}): Promise<ResultData<T>> {
  85. return this.service.get(url, { params, ..._object })
  86. }
  87. post<T>(url: string, params?: object, _object = {}): Promise<ResultData<T>> {
  88. return this.service.post(url, params, _object)
  89. }
  90. put<T>(url: string, params?: object, _object = {}): Promise<ResultData<T>> {
  91. return this.service.put(url, params, _object)
  92. }
  93. delete<T>(url: string, params?: any, _object = {}): Promise<ResultData<T>> {
  94. return this.service.delete(url, { params, ..._object })
  95. }
  96. }
  97. export default new RequestHttp(config)