http.js 2.53 KB
import axios from "axios";
import { Dialog } from "vant";
import store from "@/store";
// 测试 https://eshield.test.glsx.com.cn
// 开发
// 线上
const BASE_URL = "https://eshield.test.glsx.com.cn";
const instance = axios.create({
  // 创建axios实例,在这里可以设置请求的默认配置
  timeout: 10 * 60 * 1000, // 设置超时时间60s
  retry: 3,
  retryDelay: 1000,
});

// 统一设置post请求头
instance.defaults.headers.post["Content-Type"] = "application/json";

/** 添加请求拦截器 **/
instance.interceptors.request.use(
  (config) => {
    store.commit("showLoading");
    config.headers["Authorization"] = localStorage.getItem("token") || "";
    return config;
  },
  (error) => {
    store.commit("hideLoading");
    console.log("请求错误,原因:", error);
    return Promise.reject(error);
  }
);

/** 添加响应拦截器  **/
instance.interceptors.response.use(
  (response) => {
    store.commit("hideLoading");
    const serverCode = response.data.code,
      token = response.headers["authorization"];
    if (token || token === "") {
      localStorage.setItem("token", token);
    }
    if (serverCode === 200) {
      if (response.status) {
        return Promise.resolve(response);
      }
      return Promise.resolve(response.data);
    } else {
      Dialog({ message: response.data.message });
      return Promise.reject(response.data.message);
    }
  },
  (error) => {
    store.commit("hideLoading");
    const errRes = error.response;
    if (errRes) {
      Dialog({ message: "请求失败" });
      return Promise.reject(error);
    } else {
      Dialog({ message: "请求失败" });
      return Promise.reject(new Error("请求失败"));
    }
  }
);
const getBaseUrl = () => {
  return new Promise((resolve) => {
    resolve(BASE_URL);
  });
};

const HTTP_POST = (baseUrl, options) => {
  instance({
    url: baseUrl + options.url,
    method: "post",
    data: JSON.stringify(options.data),
  })
    .then((res) => {
      options.success(res.data);
    })
    .catch((err) => {
      options.error(err);
    });
};

const HTTP_GET = (baseUrl, options) => {
  instance({
    url: baseUrl + options.url,
    method: "get",
    params: options.data,
  })
    .then((res) => {
      options.success(res.data);
    })
    .catch((err) => {
      options.error(err);
    });
};

export default class HTTP {
  axiosPost(options) {
    getBaseUrl().then((baseUrl) => {
      HTTP_POST(baseUrl, options);
    });
  }

  axiosGet(options) {
    getBaseUrl().then((baseUrl) => {
      HTTP_GET(baseUrl, options);
    });
  }
}