request.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import axios from "axios";
  2. import { getCookie } from "@/utills/auth";
  3. import BASE from "@tools/basicTool.js";
  4. import store from "@/store";
  5. import { ElMessageBox, ElMessage } from "element-plus";
  6. // import { getToken } from "@/utils/storage";
  7. const service = axios.create();
  8. service.defaults.timeout = 50000;
  9. service.defaults.baseURL = `${process.env.VUE_APP_API}`;
  10. service.interceptors.request.use(
  11. (config) => {
  12. const t = (config.headers || {}).isToken;
  13. const u = (config.headers || {}).isUser;
  14. const isToken = t === false || t === "false";
  15. if (!isToken) {
  16. // // 让请求携带自定义token 请根据实际情况自行修改
  17. if (u) {
  18. config.headers["Authorization"] = "Bearer " + getCookie("authToken");
  19. } else {
  20. config.headers["token"] = getCookie("authToken");
  21. config.headers["userId"] = getCookie("userId");
  22. }
  23. }
  24. // 统一格式包装请求参数
  25. if (config.showLoading) {
  26. BASE.showLoading();
  27. service.defaults.showLoading = config.showLoading;
  28. }
  29. return config;
  30. },
  31. (error) => {
  32. return Promise.reject(error);
  33. }
  34. );
  35. service.interceptors.response.use(
  36. // Loading.close(),
  37. (response) => {
  38. const code = response.data.code;
  39. if (code == 401) {
  40. ElMessageBox.alert(
  41. "登录状态已过期,您可以继续留在该页面,或者重新登录",
  42. "系统提示",
  43. {
  44. confirmButtonText: "重新登录",
  45. cancelButtonText: "取消",
  46. type: "warning",
  47. callback: () => {
  48. store.dispatch("user/LogOut").then(() => {
  49. location.href = "/";
  50. });
  51. },
  52. }
  53. );
  54. } else {
  55. // 处理正常返回数据
  56. const { status } = response;
  57. if (service.defaults.showLoading) {
  58. BASE.closeLoading();
  59. service.defaults.showLoading = false;
  60. }
  61. if (status === 200) {
  62. return response.data;
  63. } else {
  64. return false;
  65. }
  66. }
  67. },
  68. (error) => {
  69. // 处理错误并给出相应的错误处理
  70. if (error.response) {
  71. console.log(error);
  72. // const { status } = error.response;
  73. // tips[status](error);
  74. return error.response.data;
  75. } else {
  76. return false;
  77. }
  78. }
  79. );
  80. export default service;