axios封装拦截

/*

 */

import axios from "axios";

import { Toast } from "vant";

import { useUserStore } from "@/store/user";

import router from "@/route";

class BaseApi {

  baseService;

  constructor({ baseURL, timeout = 60000 }) {

    const baseServiceConfig = {

      baseURL,

      timeout,

    };

    this.baseService = axios.create(baseServiceConfig);

    this._setInterceptorsRequest();

    this._setInterceptorsResponse();

  }

  get(url, params = {}) {

    return this.request(url, "get", params, {});

  }

  post(url, data = {}, withToken = true, loginMark = null) {

    const user = useUserStore();

    if (withToken) {

      data.token = user.token;

    }

    // if (loginMark) {

    //   data.loginMark = loginMark;

    // }

    // if (!!loginMark && USER_APP_CID == "") {

    //   data.loginMark = loginMark;

    // } else {

    //   data.loginMark = user.loginMark;

    // }

    data.loginMark = user.loginMark || loginMark || "";

    return this.request(url, "post", {}, data);

  }

  postFormData(url, data = {}) {

    const formData = new FormData();

    for (const key in data) {

      formData.append(key, data[key]);

    }

    const user = useUserStore();

    formData.append("loginMark", user.loginMark);

    if (!!user.token) {

      formData.append("token", user.token);

    }

    return this.request(url, "post", {}, formData, "multipart/form-data");

  }

  uploader(url, formData, withToken = true) {

    const user = useUserStore();

    if (withToken) {

      formData.append("token", user.token);

    }

    // if (loginMark) {

    //   formData.append("loginMark", loginMark);

    // }

    formData.append("loginMark", user.loginMark);

    return this.request(url, "post", {}, formData, "multipart/form-data");

  }

  request(url, method, params, data, contentType = "application/json") {

    // console.log(data);

    const headers = {

      "Content-Type": contentType,

      // "Access-Control-Allow-Origin": "*",

    };

    return this.baseService({

      method,

      url: url,

      params: params,

      data: data,

      headers,

      responseType: "json",

      // 允许为上传处理进度事件

      onUploadProgress: function (progressEvent) {

        // console.log("progressEvent", progressEvent);

      },

      // 允许为下载处理进度事件

      onDownloadProgress: function (progressEvent) {

        // console.log("progressEvent", progressEvent);

      },

    });

  }

  // 请求拦截器

  _setInterceptorsRequest() {

    this.baseService.interceptors.request.use(

      config => {

        return config;

      },

      error => {

        return Promise.reject(error);

      }

    );

  }

  // 响应拦截器

  _setInterceptorsResponse() {

    this.baseService.interceptors.response.use(

      function (response) {

        if (response.status >= 200 && response.status <= 299) {

          const { code, info: errMsg, data } = response.data;

          switch (code) {

            case 200:

              return Promise.resolve(data);

              break;

            case 410:

              // 登录失效

              Toast.fail(errMsg);

              const user = useUserStore();

              user.clearUser();

              user.$reset();

              router.push("/login");

              return romise.reject(response.data);

              break;

            default:

              Toast.fail(errMsg);

              return Promise.reject(errMsg);

              break;

          }

        }

        return Promise.reject("error");

      },

      function (error) {

        if (error.code === "ECONNABORTED" && error.message.indexOf("timeout") !== -1) {

          Toast.fail("请求超时");

          return Promise.reject("请求超时");

        }

        Toast.fail("服务器错误");

        return Promise.reject(error);

      }

    );

  }

}

// http://192.168.0.125:8081

// http://127.0.0.1:4523/mock/725336

// API_BASE_URL

//  http://127.0.0.1:4523/mock/760770

// http://192.168.31.53:4523/mock/760770

export default new BaseApi({ baseURL: API_BASE_URL });

export const dev = new BaseApi({ baseURL: "http://192.168.0.161:8088" });

使用

import api from "@/libs/BaseApi";

export function apiGetApprovalList({ categoryId = "1", pageSize = 10, pageNo = 1 }) {

  return api.post("/Hermi/leave/GetPageApplyList", {

    data: `{'categoryId':'${categoryId}','billNo':'','StartTime':'','EndTime':'','FdStartTime':'','FdEndTime':'','leaveType':'','rows':${pageSize},'page':${pageNo},'sidx':'applyDate','sord':'desc','records':0,'total':0}`,

  });

}

state.js状态

/*

 * @Desc:

 */

class STATE {

  constructor(text = "", flag = "draft", isShowWithdrawBtn = false) {

    this.text = text;

    this.flag = flag;

    this.isShowWithdrawBtn = isShowWithdrawBtn;

  }

}

const STATE_MAP = {

  0: new STATE("草稿", "draft"),

  1: new STATE("课长待审核", "pending", true),

  2: new STATE("部长待审核", "pending", true),

};

const CLOSE_FLAG_MAP = {

  0: new STATE("审核通过", "agreed"),

  1: new STATE("审核驳回", "rejected"),

};

const FINISHED_MAP_FN = {

  // 流程未结束

  0: ({ state, closeFlg }) => {

    if (state == 3) return FINISHED_MAP_FN[1]({ closeFlg });

    return STATE_MAP?.[state] ?? FINISHED_MAP_FN["none"];

  },

  // 流程结束

  1: ({ closeFlg }) => {

    return CLOSE_FLAG_MAP?.[closeFlg] ?? FINISHED_MAP_FN["none"];

  },

  // 流程撤回

  102: () => {

    return new STATE("已撤回", "draft");

  },

  none: new STATE("状态无效"),

};

/**

 * @description: 获取审批状态

 * @param {*} state 0草稿  1 课长待审核  2课长已审核、部长待审核 3审核完成

 * @param {*} closeFlg 0正常   1驳回

 * @param {*} finishedFlag 0流程未结束 1流程结束 102流程撤回

 * @return {*}

 */

export function getApprovalState_old(state, closeFlg, finishedFlag) {

  return FINISHED_MAP_FN?.[finishedFlag]({ state: state, closeFlg }) ?? FINISHED_MAP_FN["none"];

}

const STEPNO_MAP = {

  100: new STATE("草稿", "draft"),

  200: new STATE("课长待审核", "pending", true),

  300: new STATE("部长待审核", "pending", true),

  400: new STATE("本部待审核", "pending", true),

  101: new STATE("已撤回", "draft"),

  201: new STATE("课长审核驳回", "rejected"),

  210: new STATE("课长审核通过", "agreed"),

  301: new STATE("部长审核驳回", "rejected"),

  310: new STATE("部长审核通过", "agreed"),

  401: new STATE("本部审核驳回", "rejected"),

  410: new STATE("本部审核通过", "agreed"),

  none: new STATE("状态无效"),

};

/**

 * @description:

 * @param {*} stepNo

 * @return {*}

 */

export function getApprovalState(stepNo) {

  return STEPNO_MAP?.[stepNo] ?? STEPNO_MAP["none"];

}

你可能感兴趣的:(javascript,前端,vue.js)