index.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import axios, {AxiosRequestConfig} from 'axios'
  2. import {useUserStore} from '@/pinia'
  3. import {storeToRefs} from 'pinia'
  4. import router from '@/routes'
  5. const user = useUserStore()
  6. const {token} = storeToRefs(user)
  7. let instance = axios.create({
  8. baseURL: import.meta.env.VITE_API_ROOT,
  9. timeout: 50000,
  10. headers: {'Content-Type': 'application/json'},
  11. transformRequest: [function (data, headers) {
  12. if (!(headers) || headers['Content-Type'] === 'multipart/form-data;charset=UTF-8') {
  13. return data
  14. } else {
  15. headers['Content-Type'] = 'application/json'
  16. }
  17. return JSON.stringify(data)
  18. }],
  19. })
  20. instance.interceptors.request.use(
  21. config => {
  22. if (token) {
  23. (config.headers || {}).Authorization = token.value
  24. }
  25. return config
  26. },
  27. err => {
  28. return Promise.reject(err)
  29. }
  30. )
  31. instance.interceptors.response.use(
  32. response => {
  33. return Promise.resolve(response.data)
  34. },
  35. async error => {
  36. switch (error.response.status) {
  37. case 401:
  38. case 403:
  39. user.logout()
  40. await router.push('/login')
  41. break
  42. }
  43. return Promise.reject(error.response.data)
  44. }
  45. )
  46. const http = {
  47. get(url: string, config: AxiosRequestConfig = {}) {
  48. return instance.get<any, any>(url, config)
  49. },
  50. post(url: string, data: any = undefined, config: AxiosRequestConfig = {}) {
  51. return instance.post<any, any>(url, data, config)
  52. },
  53. put(url: string, data: any = undefined, config: AxiosRequestConfig = {}) {
  54. return instance.put<any, any>(url, data, config)
  55. },
  56. delete(url: string, config: AxiosRequestConfig = {}) {
  57. return instance.delete<any, any>(url, config)
  58. }
  59. }
  60. export default http