interceptor.ts 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. import axios from 'axios';
  2. import type { AxiosRequestConfig, AxiosResponse } from 'axios';
  3. import { Message, Modal } from '@arco-design/web-vue';
  4. import { useUserStore } from '@/store';
  5. import { getAuthorization, getToken, setAuthorization } from "@/utils/auth";
  6. export interface HttpResponse<T = unknown> {
  7. status: number;
  8. msg: string;
  9. code: number;
  10. data: T;
  11. }
  12. if (import.meta.env.VITE_API_BASE_URL) {
  13. axios.defaults.baseURL = import.meta.env.VITE_API_BASE_URL;
  14. }
  15. axios.interceptors.request.use(
  16. (config: AxiosRequestConfig) => {
  17. // let each request carry token
  18. // this example using the JWT token
  19. // Authorization is a custom headers key
  20. // please modify it according to the actual situation
  21. // const token = getToken();
  22. // if (token) {
  23. // if (!config.headers) {
  24. // config.headers = {};
  25. // }
  26. // config.headers.Authorization = `Bearer ${token}`;
  27. // }
  28. const authorization = getAuthorization();
  29. if (authorization) {
  30. if (!config.headers) {
  31. config.headers = {};
  32. }
  33. config.headers.Authorization = authorization;
  34. config.headers.token = getToken();
  35. }
  36. return config;
  37. },
  38. (error) => {
  39. // do something
  40. return Promise.reject(error);
  41. }
  42. );
  43. // add response interceptors
  44. axios.interceptors.response.use(
  45. (response: AxiosResponse<HttpResponse>) => {
  46. const res = response.data;
  47. // if the custom code is not 20000, it is judged as an error.
  48. if ((res.retcode && res.retcode !== 0) || (res.code && res.code !== 20000)) {
  49. Message.error({
  50. content: res.msg || 'Error',
  51. duration: 5 * 1000,
  52. });
  53. // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
  54. if (
  55. [50008, 50012, 50014].includes(res.code) &&
  56. response.config.url !== '/api/user/info'
  57. ) {
  58. Modal.error({
  59. title: 'Confirm logout',
  60. content:
  61. 'You have been logged out, you can cancel to stay on this page, or log in again',
  62. okText: 'Re-Login',
  63. async onOk() {
  64. const userStore = useUserStore();
  65. await userStore.logout();
  66. window.location.reload();
  67. },
  68. });
  69. }
  70. return Promise.reject(new Error(res.msg || 'Error'));
  71. }
  72. if(response.config.url === '/v1/user/login') {
  73. setAuthorization(response.headers.authorization);
  74. }
  75. return res;
  76. },
  77. (error) => {
  78. Message.error({
  79. content: error.msg || 'Request Error',
  80. duration: 5 * 1000,
  81. });
  82. return Promise.reject(error);
  83. }
  84. );