index.ts 4.0 KB

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