request.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. import axios from 'axios';
  2. import { notification } from 'ant-design-vue';
  3. import Common from '../common/Common.js';
  4. // 创建 axios 实例
  5. const request = axios.create({
  6. // API 请求的默认前缀
  7. baseURL: '/',
  8. timeout: 60000, // 请求超时时间
  9. });
  10. // 异常拦截处理器
  11. const errorHandler = error => {
  12. console.log(error);
  13. if (error.response) {
  14. const data = error.response.data;
  15. // 从 localstorage 获取 token
  16. const token = localStorage.getItem('#token');
  17. if (error.response.status === 403) {
  18. notification.error({
  19. message: 'Forbidden',
  20. description: data.message,
  21. });
  22. }
  23. if (error.response.status === 401 && !(data.result && data.result.isLogin)) {
  24. console.log('401');
  25. notification.error({
  26. message: 'Unauthorized',
  27. description: 'Authorization verification failed',
  28. });
  29. if (token) {
  30. // store.dispatch('Logout').then(() => {
  31. // setTimeout(() => {
  32. // window.location.reload();
  33. // }, 1500);
  34. // });
  35. }
  36. }
  37. }
  38. return Promise.reject(error);
  39. };
  40. // request interceptor
  41. request.interceptors.request.use(config => {
  42. const token = localStorage.getItem('#token');
  43. // 如果 token 存在
  44. // 让每个请求携带自定义 token 请根据实际情况自行修改
  45. if (token) {
  46. config.headers['token'] = token;
  47. }
  48. return config;
  49. }, errorHandler);
  50. // 异常拦截处理器
  51. const responseErrorHandler = error => {
  52. console.log(error);
  53. if (error.response.status === 401) {
  54. const currentUrl = window.location.href;
  55. if (currentUrl.indexOf('login') < 0 && currentUrl.indexOf('redirectUrl=') < 0) {
  56. // window.location = Common.getRedirectUrl('#/login?redirectUrl=' + encodeURIComponent(currentUrl));
  57. const isOut = localStorage.getItem('isOut');
  58. console.log(isOut, '9999999999999');
  59. if (isOut == 'true') {
  60. window.location = Common.getRedirectUrl('#/login?isOut=true&redirectUrl=' + encodeURIComponent(currentUrl));
  61. } else {
  62. window.location = Common.getRedirectUrl('#/login?isOut=false&redirectUrl=' + encodeURIComponent(currentUrl));
  63. }
  64. }
  65. }
  66. if (error.response.status === 504) {
  67. notification.error({
  68. message: '504',
  69. description: error.response.data,
  70. });
  71. }
  72. return Promise.reject(error);
  73. };
  74. // response interceptor
  75. request.interceptors.response.use(response => {
  76. return response.data;
  77. }, responseErrorHandler);
  78. export default request;