request.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /**
  2. * axios 实例
  3. */
  4. import axios from 'axios';
  5. import router from '@/router';
  6. import store from '@/store';
  7. import { MessageBox, Message } from 'element-ui';
  8. import { API_BASE_URL, TOKEN_HEADER_NAME, LAYOUT_PATH } from '@/config/setting';
  9. import { getToken, setToken } from './token-util';
  10. import { logout } from './page-tab-util';
  11. import JSONBIG from 'json-bigint';
  12. const service = axios.create({
  13. baseURL: API_BASE_URL,
  14. transformResponse: [
  15. function (data) {
  16. if (data instanceof Blob) {
  17. return data;
  18. }
  19. const json = JSONBIG({
  20. storeAsString: true
  21. });
  22. const res = json.parse(data);
  23. return res;
  24. }
  25. ]
  26. });
  27. /**
  28. * 添加请求拦截器
  29. */
  30. service.interceptors.request.use(
  31. (config) => {
  32. // 添加 token 到 header
  33. const token = getToken();
  34. if (token && config.headers) {
  35. config.headers.common[TOKEN_HEADER_NAME] = token;
  36. }
  37. return config;
  38. },
  39. (error) => {
  40. return Promise.reject(error);
  41. }
  42. );
  43. /**
  44. * 添加响应拦截器
  45. */
  46. service.interceptors.response.use(
  47. (res) => {
  48. // token 自动续期
  49. if (Number(res.data.code) == -1 && res.config?.showErrorToast !== false) {
  50. Message.error(res.data.message);
  51. return false;
  52. }
  53. const token = res.headers[TOKEN_HEADER_NAME.toLowerCase()];
  54. if (token) {
  55. setToken(token);
  56. }
  57. return res;
  58. },
  59. (error) => {
  60. // 登录过期处理
  61. if (error?.response?.status === 401) {
  62. const currentPath = router.currentRoute.path;
  63. if (currentPath === LAYOUT_PATH) {
  64. logout(true);
  65. } else {
  66. MessageBox.alert('登录状态已过期, 请退出重新登录!', '系统提示', {
  67. confirmButtonText: '重新登录',
  68. callback: (action) => {
  69. if (action === 'confirm') {
  70. logout(false, currentPath);
  71. }
  72. },
  73. beforeClose: () => {
  74. MessageBox.close();
  75. }
  76. });
  77. }
  78. return Promise.reject(new Error(error.response.data?.message));
  79. }
  80. return Promise.reject(error);
  81. }
  82. );
  83. export default service;