index.ts 1.9 KB

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