request.js 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. import axios from 'axios'
  2. import { ElMessage } from 'element-plus'
  3. import { useLangStore } from '@/pinia/langStore'
  4. import { useAppStore } from '@/pinia/appStore'
  5. // 创建 axios 实例
  6. const request = axios.create({
  7. baseURL: import.meta.env.VITE_API_BASE_URL,
  8. timeout: 10000,
  9. headers: {
  10. 'Content-Type': 'application/json;charset=UTF-8'
  11. }
  12. })
  13. // 请求拦截器
  14. request.interceptors.request.use(
  15. config => {
  16. // 获取 token(假设存储在 localStorage 中)
  17. const token = localStorage.getItem('token')
  18. if (token) {
  19. config.headers.Authorization = `Bearer ${token}`
  20. }
  21. const langStore = useLangStore();
  22. config.headers['Accept-Language'] = langStore.currentLang==='en'?'en':'zh';
  23. // 处理请求参数
  24. if (config.method === 'get' && config.params) {
  25. // 过滤掉空值参数
  26. // const filteredParams = {}
  27. // Object.keys(config.params).forEach(key => {
  28. // if (config.params[key] !== null && config.params[key] !== undefined && config.params[key] !== '') {
  29. // filteredParams[key] = config.params[key]
  30. // }
  31. // })
  32. // config.params = filteredParams
  33. }
  34. // 支持 formData
  35. if (config.data instanceof FormData) {
  36. // 如果是 FormData 类型,移除默认的 Content-Type,让浏览器自动设置
  37. delete config.headers['Content-Type']
  38. }
  39. return config
  40. },
  41. error => {
  42. console.error('请求错误:', error)
  43. return Promise.reject(error)
  44. }
  45. )
  46. // 响应拦截器
  47. request.interceptors.response.use(
  48. response => {
  49. const appStore = useAppStore();
  50. // 根据后端约定的响应结构进行状态判断
  51. const { code, data, msg } = response.data
  52. // 假设 code 为 200 表示成功
  53. if (code === 200) {
  54. return response.data
  55. } else if ([410000, 410001, 410002, 401, 403].includes(code)){
  56. appStore.LOGOUT();
  57. localStorage.removeItem('token')
  58. //弹出登录框
  59. appStore.showLoginDialog = true;
  60. // window.location.href = '/login'
  61. return response.data
  62. }else {
  63. ElMessage.error(msg|| '请求失败')
  64. return response.data
  65. }
  66. },
  67. error => {
  68. console.error('响应错误:', error)
  69. // HTTP 状态码错误处理
  70. if (error.response) {
  71. const { status, data } = error.response
  72. switch (status) {
  73. case 401:
  74. // 未授权
  75. localStorage.removeItem('token')
  76. break
  77. case 403:
  78. // 禁止访问
  79. console.error('禁止访问:', data.message)
  80. break
  81. case 404:
  82. // 资源不存在
  83. console.error('请求资源不存在')
  84. break
  85. case 500:
  86. // 服务器内部错误
  87. console.error('服务器内部错误')
  88. break
  89. default:
  90. console.error(`连接错误:${status}`)
  91. }
  92. } else if (error.request) {
  93. // 请求发出但没有收到响应
  94. console.error('网络错误,请检查网络连接')
  95. } else {
  96. // 其他错误
  97. console.error('请求失败:', error.message)
  98. }
  99. return Promise.reject(error)
  100. }
  101. )
  102. /**
  103. * GET 请求
  104. * @param {string} url 请求地址
  105. * @param {object} params 请求参数
  106. * @param {object} config 其他配置
  107. */
  108. export function get(url, params = {}, config = {}) {
  109. return request({
  110. method: 'get',
  111. url,
  112. params,
  113. ...config
  114. })
  115. }
  116. /**
  117. * POST 请求
  118. * @param {string} url 请求地址
  119. * @param {object} data 请求数据
  120. * @param {object} config 其他配置
  121. */
  122. export function post(url, data = {}, config = {}) {
  123. return request({
  124. method: 'post',
  125. url,
  126. data,
  127. ...config
  128. })
  129. }
  130. /**
  131. * PUT 请求
  132. * @param {string} url 请求地址
  133. * @param {object} data 请求数据
  134. * @param {object} config 其他配置
  135. */
  136. export function put(url, data = {}, config = {}) {
  137. return request({
  138. method: 'put',
  139. url,
  140. data,
  141. ...config
  142. })
  143. }
  144. /**
  145. * DELETE 请求
  146. * @param {string} url 请求地址
  147. * @param {object} params 请求参数
  148. * @param {object} config 其他配置
  149. */
  150. export function del(url, params = {}, config = {}) {
  151. return request({
  152. method: 'delete',
  153. url,
  154. params,
  155. ...config
  156. })
  157. }
  158. export default {
  159. get,
  160. post,
  161. put,
  162. del
  163. }