index.ts 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import axios from 'axios'
  2. import sso from './sso'
  3. import router from '@src/router/index'
  4. import type { AxiosInstance, CreateAxiosDefaults, AxiosRequestConfig } from 'axios'
  5. const config = {
  6. timeout: 60000,
  7. }
  8. const invalidCode = 1000
  9. class Request {
  10. private instance: AxiosInstance
  11. constructor(config: CreateAxiosDefaults) {
  12. this.instance = axios.create(config)
  13. this.instance.interceptors.request.use(function(config) {
  14. if (!config.headers.token) {
  15. const userInfo = sso.getUserInfo()
  16. config.headers.token = userInfo.token
  17. }
  18. return config
  19. }, function(error) {
  20. return Promise.reject(error)
  21. })
  22. this.instance.interceptors.response.use(function(response) {
  23. const { data } = response
  24. const { code } = data
  25. // 登陆过期 || 未登陆
  26. if (code === invalidCode) {
  27. sso.clearUserInfo()
  28. const {pathname,search} = location
  29. if (pathname!=='/login') {
  30. router.navigate('/login?redirectUrl='+ encodeURIComponent(pathname+search) )
  31. }
  32. return Promise.reject(data)
  33. }
  34. return data
  35. }, function(error) {
  36. return Promise.reject(error)
  37. })
  38. }
  39. get<T>(url: string, config?: AxiosRequestConfig): Promise<ApiResponse<T>> {
  40. return this.instance.get(url, config)
  41. }
  42. getBlob<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
  43. return this.instance.get(url, config)
  44. }
  45. post<T>(url: string, data?: unknown, config?: AxiosRequestConfig): Promise<ApiResponse<T>> {
  46. return this.instance.post(url, data, config)
  47. }
  48. }
  49. export default new Request(config)