client.ts 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import axios from 'axios'
  2. import { useAuthStore } from '../stores/auth'
  3. import { ElMessage } from 'element-plus'
  4. const api = axios.create({
  5. baseURL: '/api',
  6. timeout: 0, // 0 = no timeout
  7. headers: { 'Content-Type': 'application/json' },
  8. })
  9. api.interceptors.request.use((config) => {
  10. const auth = useAuthStore()
  11. if (auth.token) {
  12. config.headers.Authorization = `Bearer ${auth.token}`
  13. }
  14. return config
  15. })
  16. api.interceptors.response.use(
  17. (res) => {
  18. const body = res.data
  19. if (body.code !== 0 && body.code !== undefined) {
  20. ElMessage.error(body.msg || '请求失败')
  21. return Promise.reject(new Error(body.msg))
  22. }
  23. return body
  24. },
  25. (err) => {
  26. if (err.response?.status === 401) {
  27. const auth = useAuthStore()
  28. auth.logout()
  29. if (window.location.pathname !== '/login') {
  30. window.location.href = '/login'
  31. }
  32. } else if (err.response?.status === 403 && err.response?.data?.detail === '用户已被禁用') {
  33. const auth = useAuthStore()
  34. auth.logout()
  35. ElMessage.error('账号已被禁用,请联系管理员')
  36. if (window.location.pathname !== '/login') {
  37. window.location.href = '/login'
  38. }
  39. } else {
  40. ElMessage.error(err.response?.data?.detail || err.message || '网络异常')
  41. }
  42. return Promise.reject(err)
  43. },
  44. )
  45. export default api