index.ts 4.8 KB

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