http.ts 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. import axios from "axios";
  2. import history from "./history";
  3. import { getTokenInfo, removeTokenInfo } from "./storage";
  4. import store from "@/store";
  5. import { MessageFu } from "./message";
  6. // 请求基地址
  7. export const baseURL =
  8. // 线下的图片地址需要加上/api/
  9. // process.env.NODE_ENV === "development"
  10. // ? "http://192.168.20.55:8040/api/"
  11. // : "";
  12. // process.env.NODE_ENV === "development" ? "https://jszhongyi.4dage.com" : "";
  13. process.env.NODE_ENV === "development" ? "https://xuzhouwall.4dage.com" : "";
  14. // 处理 类型“AxiosResponse<any, any>”上不存在属性“code”
  15. declare module "axios" {
  16. interface AxiosResponse {
  17. code: number;
  18. // 这里追加你的参数
  19. }
  20. }
  21. // 创建 axios 实例
  22. const http = axios.create({
  23. // --------线下的地址不用加/api/
  24. // baseURL: baseURL,
  25. // --------打包或线上环境接口需要加上api/
  26. baseURL: baseURL + "/api/",
  27. timeout: 5000,
  28. });
  29. let axajInd = 0;
  30. // 请求拦截器
  31. http.interceptors.request.use(
  32. function (config: any) {
  33. // 发请求前打开加载提示
  34. store.dispatch({ type: "login/asyncLoding", payload: true });
  35. axajInd++;
  36. const { token } = getTokenInfo();
  37. if (token) config.headers.token = token;
  38. return config;
  39. },
  40. function (err) {
  41. return Promise.reject(err);
  42. }
  43. );
  44. let timeId = -1;
  45. // 响应拦截器
  46. http.interceptors.response.use(
  47. function (response) {
  48. // 请求回来的关闭加载提示
  49. axajInd--;
  50. if (axajInd === 0) {
  51. store.dispatch({ type: "login/asyncLoding", payload: false });
  52. }
  53. if (response.data.code === 5001 || response.data.code === 5002) {
  54. clearTimeout(timeId);
  55. timeId = window.setTimeout(() => {
  56. removeTokenInfo();
  57. MessageFu.warning("登录失效!");
  58. history.push("/login");
  59. }, 200);
  60. } else if (response.data.code === 0) {
  61. // MessageFu.success(response.data.msg);
  62. } else if (response.data.code === 3014)
  63. MessageFu.warning("用户名不存在或密码错误,请联系管理员!");
  64. else MessageFu.warning(response.data.msg);
  65. return response.data;
  66. },
  67. async function (err) {
  68. axajInd = 0;
  69. store.dispatch({ type: "login/asyncLoding", payload: false });
  70. // 上传附件的进度条
  71. const UpAsyncLodingDom: any = document.querySelector("#UpAsyncLoding");
  72. const progressDom: any = document.querySelector("#progress");
  73. // 如果因为网络原因,response没有,给提示消息
  74. if (!err.response) {
  75. MessageFu.warning("网络繁忙,请稍后重试!");
  76. } else {
  77. MessageFu.warning("错误!");
  78. }
  79. // 响应错误也要取消 上传文件的进度条
  80. UpAsyncLodingDom.style.opacity = 0;
  81. progressDom.style.width = "0%";
  82. return Promise.reject(err);
  83. }
  84. );
  85. // 导出 axios 实例
  86. export default http;