index.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import { type CreateAxiosDefaults } from 'axios'
  2. import { Request, type RequestConfig, type RequestError } from '@jg_widgets/utils'
  3. import { Message } from 'element-ui'
  4. // import { PAGE_PATH, UN_AUTH_PATH } from '../../config'
  5. // import { userService } from '../index'
  6. import cache from '../../utils/cache'
  7. class App extends Request {
  8. constructor (config: CreateAxiosDefaults & RequestConfig) {
  9. const handleError = (nErr: RequestError, err: any) => {
  10. if (['401'].includes(nErr.code)) {
  11. // this.navigateReplace(`${PAGE_PATH.login}?redirect=${location.pathname}`)
  12. } else {
  13. Message.error(nErr.message)
  14. }
  15. }
  16. super(
  17. {
  18. loading: false,
  19. cancel: false,
  20. headers: {
  21. Authorization: 'Bearer ' + cache.session.get('token')
  22. },
  23. ...config
  24. },
  25. {
  26. handleError,
  27. addHeader: () => [
  28. // { key: 'token', value: userService.userInfo?.token ?? '', whitelist: UN_AUTH_PATH }
  29. ],
  30. responseInterceptor: response => {
  31. response.use(
  32. res => {
  33. console.log(res,'响应数据');
  34. if (['200', 0].includes(res?.data?.code)) {
  35. return Promise.resolve(res.data.data ?? null)
  36. }
  37. const err = new Error(res?.data?.msg || '')
  38. handleError(super.getError(err), err)
  39. return Promise.reject(err)
  40. },
  41. err => Promise.reject(err)
  42. )
  43. }
  44. }
  45. )
  46. }
  47. navigatePush (url: string) {
  48. url && (window.location.href = url)
  49. }
  50. navigateReplace (url: string) {
  51. url && window.location.replace(url)
  52. }
  53. getCache = (key: string, type: 'session' | 'local' = 'session') => {
  54. const data = type === 'session' ? sessionStorage.getItem(key) : localStorage.getItem(key)
  55. return data ? JSON.parse(data) : null
  56. }
  57. setCache = (key: string, value: any, type: 'session' | 'local' = 'session') => {
  58. if (!value) {
  59. type === 'session' ? sessionStorage.removeItem(key) : localStorage.removeItem(key)
  60. } else {
  61. type === 'session'
  62. ? sessionStorage.setItem(key, JSON.stringify(value))
  63. : localStorage.setItem(key, JSON.stringify(value))
  64. }
  65. }
  66. }
  67. export default App