ajax.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import axios from 'axios';
  2. import { kuky_Authorization } from './storage';
  3. import replaceProxyUrl from './ajax/replace-proxy-url';
  4. import { backToLogin } from './ajax/back-to-login';
  5. const ajax = axios.create({
  6. withCredentials: true, // 跨域发送 cookie
  7. timeout: 300000, // 请求超时
  8. headers: {
  9. 'Content-Type': 'application/json'
  10. }
  11. });
  12. ajax.interceptors.request.use(
  13. (config) => {
  14. replaceProxyUrl(config);
  15. const token = kuky_Authorization.get();
  16. if (token) {
  17. config.headers['Authorization'] = `Bearer ${token}`;
  18. }
  19. return config;
  20. },
  21. (error) => {
  22. // 请求出错
  23. return Promise.reject(error);
  24. }
  25. );
  26. ajax.interceptors.response.use(
  27. (response) => {
  28. const res_data = response.data;
  29. const { code, data, msg } = res_data;
  30. if (res_data.code == '401' || res_data.retcode == '401') {
  31. // 回到登录页面
  32. backToLogin();
  33. }
  34. return res_data;
  35. },
  36. (error) => {
  37. if (error.message.includes('401')) {
  38. backToLogin();
  39. }
  40. if (error.status === 401) {
  41. backToLogin();
  42. }
  43. return Promise.reject(error);
  44. }
  45. );
  46. export default ajax;