request.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. const json = JSONBIG({
  17. storeAsString: true
  18. });
  19. const res = json.parse(data);
  20. return res;
  21. }
  22. ]
  23. });
  24. /**
  25. * 添加请求拦截器
  26. */
  27. service.interceptors.request.use(
  28. (config) => {
  29. // 添加 token 到 header
  30. const token = getToken();
  31. if (token && config.headers) {
  32. config.headers.common[TOKEN_HEADER_NAME] = token;
  33. }
  34. config.headers['Submit-Time'] = store.state.pageTimstamp;
  35. return config;
  36. },
  37. (error) => {
  38. return Promise.reject(error);
  39. }
  40. );
  41. /**
  42. * 添加响应拦截器
  43. */
  44. service.interceptors.response.use(
  45. (res) => {
  46. // token 自动续期
  47. if (res.data.code == '-1' && res.config?.showErrorToast !== false) {
  48. Message.error(res.data.message);
  49. }
  50. const token = res.headers[TOKEN_HEADER_NAME.toLowerCase()];
  51. if (token) {
  52. setToken(token);
  53. }
  54. return res;
  55. },
  56. (error) => {
  57. // 登录过期处理
  58. if (error?.response?.status === 401) {
  59. const currentPath = router.currentRoute.path;
  60. if (currentPath === LAYOUT_PATH) {
  61. logout(true);
  62. } else {
  63. MessageBox.alert('登录状态已过期, 请退出重新登录!', '系统提示', {
  64. confirmButtonText: '重新登录',
  65. callback: (action) => {
  66. if (action === 'confirm') {
  67. logout(false, currentPath);
  68. }
  69. },
  70. beforeClose: () => {
  71. MessageBox.close();
  72. }
  73. });
  74. }
  75. return Promise.reject(new Error(error.response.data?.message));
  76. }
  77. return Promise.reject(error);
  78. }
  79. );
  80. export default service;