封装axios方法

44 阅读3分钟
import { message, Modal } from "ant-design-vue";
import axios, { AxiosError, AxiosRequestConfig, AxiosResponse } from "axios";
// @ts-ignore
import axiosRetry from "axios-retry";
import { contentType, dataName, messageName, requestTimeout, statusName, successName } from "@/config/network";
import { noShowApiMessage, noShowApiMessageSuccess } from "@/config/custom";
import i18n from "@/locales/i18n";
import router from "@/router/index";
import store from "@/store";
import { AjaxRes } from "@/types/common";
import { createSign, getSessionId } from "@/utils/clientStorage";
import { isContainChinese } from "@/utils/network";
//* ************************axios配置  拦截器*****************************//
axios.defaults.baseURL = process.env.VUE_APP_BASE_API;
// 前端超时限制
axios.defaults.timeout = requestTimeout;
axios.defaults.headers["Content-Type"] = contentType;
// http请求拦截器
axios.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    const token = store && store.state["user"].token;
    const language = store && store.state["app"].language;
    const website = store && store.state["app"].website;
    const currency = store && store.state["app"].currency;
    const SessionId = getSessionId() as string;
    config.headers = {
      Language: currency === "EUR" ? "eu" : language,
      Website: website,
      Currency: currency,
      token: token,
    };
    if (SessionId) config.headers["SessionId"] = SessionId;
    if (token) {
      config.headers["Authorization"] = `Bearer ${token}`;
    }
    // 去除传递参数空格操作
    if (config.data && Object.keys(config.data).length > 0) {
      Object.keys(config.data).forEach((item: string) => {
        if (typeof config.data[item] === "string") config.data[item] = config.data[item].trim();
      });
    }
    if (config.params && Object.keys(config.params).length > 0) {
      Object.keys(config.params).forEach((item: string) => {
        if (typeof config.params[item] === "string") config.params[item] = config.params[item].trim();
      });
    }
    return { ...config, url: createSign(config.url as string) };
  },
  (error: AxiosError) => {
    return Promise.reject(error);
  }
);
// http响应拦截器
axios.interceptors.response.use(
  (response: AxiosResponse) => {
    if (response.headers._token && response.config.url !== "/api/base/v1/simplelogin") {
      store.commit("user/setTokenInfo", response.headers._token);
    }
    switch (response.data[statusName]) {
      case 401:
        break;
      case 403:
        break;
      case 404:
        message.error(response.data[messageName]);
        break;
      case 500:
        //登录页面的部分接口不提示 存在中文key给提示
        (!location.pathname.includes("/auth/") || !noShowApiMessage.some((t) => (response.config.url as string).includes(t))) &&
          isContainChinese(response.data[messageName]) &&
          Modal.error({
            title: i18n.t("接口温馨提醒"),
            content: i18n.t(response.data[messageName] ? String(response.data[messageName]) : "接口发生异常"),
            centered: true,
            okText: i18n.t("确定") as string,
          });
        break;
      default:
        if (response.data[messageName] && response.data[successName] && !response.data[dataName]) {
          if (!noShowApiMessageSuccess.some((t) => (response.config.url as string).includes(t))) {
            // @ts-ignore
            message.success(i18n.t(String(response.data[messageName]) || "操作成功") || i18n.t("操作成功"));
          }
        }
        if (response.data[messageName] && !response.data[successName] && !response.data[dataName] && isContainChinese(response.data[messageName])) {
          Modal.error({
            title: i18n.t("接口温馨提醒"),
            content: i18n.t(response.data[messageName] ? String(response.data[messageName]) : "接口发生异常") || i18n.t("接口发生异常"),
            centered: true,
            okText: i18n.t("确定") as string,
          });
        }
        break;
    }
    return response;
  },
  (error: AxiosError) => {
    // if (error.response && error.response.status === 401) {
    // }
    // 403 无权限
    if (error.response && error.response.status === 403) {
      message.warning(error.response.statusText);
    }
    // 404 请求不存在
    if (error.response && error.response.status === 404) {
      message.warning(error.response.statusText);
    }
    // 405 请求方法不允许
    if (error.response && error.response.status === 405) {
      message.warning(error.response.statusText);
    }
    // 415 Unsupported Media Type co
    if (error.response && error.response.status === 415) {
      message.warning(error.response.statusText);
    }
    //服务器没有能力完成请求
    if (error.response && error.response.status === 501) {
      //跳到 501 页面
      router.push("/exception/501").then(() => {});
    }
    if (error.response && [504, 502, 500, 400].includes(error.response.status)) {
      //跳到 500 页面
      router.push("/exception/500").then(() => {});
    }
    return Promise.reject(error);
  }
);
//* ************************axios配置  拦截器*****************************//
// const params = new URLSearchParams();
// params.append('param1', 'value1');
// params.append('param2', 'value2');
axiosRetry(axios, {
  retries: 3,
  retryDelay: (retryCount: number) => {
    return retryCount * 1500; // 重复请求延迟(毫秒)
  },
  shouldResetTimeout: true, //  重置超时时间
  retryCondition: (error: AxiosError) => {
    //true为打开自动发送请求,false为关闭自动发送请求
    return error.message.includes("timeout") || error.message.includes("Network Error");
  },
});
/**
 *  封装 axios 自定义请求
 * @param url
 * @param Method
 * @param params
 * @param data
 */
export const ajax = ({ url, method = "GET", params = {}, data = {}, baseURL = undefined, headers = {}, responseType = "json" }: AxiosRequestConfig): Promise<AjaxRes> => {
  return new Promise((resolve, reject) => {
    axios({
      url,
      method,
      params,
      baseURL,
      headers,
      data,
      withCredentials: true,
      responseType, // default json  options are: 'arraybuffer', 'document', 'json', 'text', 'stream'  browser only: 'blob'
      validateStatus: function (status: number) {
        return status >= 200 && status < 300; // default
      },
    })
      .then((response: AxiosResponse) => {
        resolve(response.data);
      })
      .catch((error: AxiosError) => {
        // 错误信息reject出去 在catch中接受
        reject(error.response);
      });
  });
};


import { ajax } from "@/api/ajax";
import { paramsSerialize } from "@/api/serialize";
import { AjaxRes } from "@/types/common";

export const ajaxGet = (url: string, params = {}): Promise<AjaxRes> => ajax({ method: "get", url, params });

export const ajaxDelete = (url: string, params = {}, data = {}): Promise<AjaxRes> => ajax({ method: "delete", url, params, data });

export const ajaxPost = (url: string, params = {}, data = {}, paramsSerialization = false): Promise<AjaxRes> =>
  ajax({
    method: "post",
    url,
    params,
    data: paramsSerialize(paramsSerialization, data),
    headers: {
      "Content-Type": paramsSerialization ? "application/x-www-form-urlencoded;charset=UTF-8" : "application/json;charset=UTF-8",
    },
  });

export const ajaxPut = (url: string, data = {}, paramsSerialization = false, params = {}): Promise<AjaxRes> =>
  ajax({
    method: "put",
    url,
    params,
    data: paramsSerialize(paramsSerialization, data),
    headers: {
      "Content-Type": paramsSerialization ? "application/x-www-form-urlencoded;charset=UTF-8" : "application/json;charset=UTF-8",
    },
  });

export const ajaxPatch = (url: string, data = {}, paramsSerialization = false, params = {}): Promise<AjaxRes> =>
  ajax({
    method: "patch",
    url,
    params,
    data: paramsSerialize(paramsSerialization, data),
    headers: {
      "Content-Type": paramsSerialization ? "application/x-www-form-urlencoded;charset=UTF-8" : "application/json;charset=UTF-8",
    },
  });

import qs from "qs";

/**
 * 数据是否进行序列化转换
 * @param paramsSerialization 是否进行序列化
 * @param data 数据
 * @returns {*}
 */
export const paramsSerialize = (paramsSerialization: boolean, data: Record<string, unknown>) => (paramsSerialization ? qs.stringify(data) : data);


export interface AjaxRes {
  code: number;
  // eslint-disable-next-line
  data: any | null;
  success: boolean;
  timestamp: string;
  message: string;
}