index.ts 1.7 KB

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