request.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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 (res.data.code == '-1' && res.config?.showErrorToast !== false) {
  50. Message.error(res.data.message);
  51. }
  52. const token = res.headers[TOKEN_HEADER_NAME.toLowerCase()];
  53. if (token) {
  54. setToken(token);
  55. }
  56. return res;
  57. },
  58. (error) => {
  59. // 登录过期处理
  60. if (error?.response?.status === 401) {
  61. const currentPath = router.currentRoute.path;
  62. if (currentPath === LAYOUT_PATH) {
  63. logout(true);
  64. } else {
  65. MessageBox.alert('登录状态已过期, 请退出重新登录!', '系统提示', {
  66. confirmButtonText: '重新登录',
  67. callback: (action) => {
  68. if (action === 'confirm') {
  69. logout(false, currentPath);
  70. }
  71. },
  72. beforeClose: () => {
  73. MessageBox.close();
  74. }
  75. });
  76. }
  77. return Promise.reject(new Error(error.response.data?.message));
  78. }
  79. return Promise.reject(error);
  80. }
  81. );
  82. export default service;