request.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import router from '@/router'
  2. import axios from "axios";
  3. import { Notify } from "vant";
  4. import axiosRetry from "axios-retry";
  5. // 获取环境变量
  6. export const getBaseURI = () => {
  7. let env = process.env.VUE_APP_NODE_ENV || process.env.NODE_ENV;
  8. // 开发环境
  9. if (env === "dev" || env == "development") {
  10. // return 'http://192.168.1.51:9013/witcarbon-app';
  11. return "http://gpu.ringzle.com:8082/witcarbon-app";
  12. }
  13. // 集成测试环境
  14. if (env === "prod:sit") {
  15. return "https://s.ringzle.com/stayhome-app";
  16. }
  17. if (env === "prod:uat") {
  18. return "https://s.ringzle.com/stayhome-app";
  19. }
  20. // 生产环境
  21. if (env === "prod" || env === "production") {
  22. return "/stayhome-app";
  23. }
  24. };
  25. export const BaseUrl = getBaseURI();
  26. export const service = axios.create({
  27. timeout: 10000,
  28. timeoutErrorMessage: "请求超时,请检查网络后重试",
  29. baseURL: getBaseURI(),
  30. });
  31. /**
  32. * req 拦截器
  33. */
  34. service.interceptors.request.use(
  35. (config) => {
  36. // 配置头部
  37. let token = window.localStorage.getItem("token");
  38. if (token != "") {
  39. config.headers["token"] = token;
  40. }
  41. return config;
  42. },
  43. (error) => {
  44. Notify({ type: "danger", message: JSON.stringify(error) });
  45. return Promise.resolve(error);
  46. }
  47. );
  48. /**
  49. * res 拦截器
  50. */
  51. service.interceptors.response.use((response) => {
  52. const res = response.data;
  53. // 判断token 失效
  54. if (res.code == 10021 || res.code == 10004) {
  55. localStorage.clear()
  56. window.location.href = "/#/login"
  57. Notify({ type: "danger", message: res.msg });
  58. }
  59. if (res.code == 500) {
  60. Notify({ type: "danger", message: res.msg });
  61. }
  62. if (res.error) {
  63. Notify({ type: "danger", message: JSON.stringify(res) });
  64. return Promise.resolve(res);
  65. }
  66. return Promise.resolve(res);
  67. });
  68. axiosRetry(service, {
  69. retries: 3, // 设置自动发送请求次数
  70. retryDelay: () => 300, // 重新请求的间隔
  71. shouldResetTimeout: true, // 重置超时时间
  72. retryCondition: (error) => {
  73. // true为打开自动发送请求,false为关闭自动发送请求
  74. if (error.message.includes("timeout")) return true;
  75. // 如果你要在请求出错的时候重新发送请求(返回400以上的状态码时) 你应该像下面这样写
  76. if (
  77. error.message.includes("timeout") ||
  78. error.message.includes("status code")
  79. )
  80. return true;
  81. },
  82. });