request.js 2.3 KB

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