request.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. console.log(res,'res')
  49. // token 自动续期
  50. if (res.data.code == '-1' && res.config?.showErrorToast !== false&&res.data.message) {
  51. Message.error(res.data.message);
  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. console.log(error,'error')
  62. if (error?.response?.status === 401) {
  63. const currentPath = router.currentRoute.path;
  64. if (currentPath === LAYOUT_PATH) {
  65. logout(true);
  66. } else {
  67. MessageBox.alert('登录状态已过期, 请退出重新登录!', '系统提示', {
  68. confirmButtonText: '重新登录',
  69. callback: (action) => {
  70. if (action === 'confirm') {
  71. logout(false, currentPath);
  72. }
  73. },
  74. beforeClose: () => {
  75. MessageBox.close();
  76. }
  77. });
  78. }
  79. return Promise.reject(new Error(error.response.data?.message));
  80. }else if(!error?.response?.status){
  81. Message.error('服务调用失败,请联系管理员!');
  82. }
  83. return Promise.reject(error);
  84. }
  85. );
  86. export default service;