vben
2021-02-22 be3a3ed699f73d352d49623ef07288093a3332c4
src/utils/http/axios/index.ts
@@ -3,9 +3,7 @@
import type { AxiosResponse } from 'axios';
import type { CreateAxiosOptions, RequestOptions, Result } from './types';
import { VAxios } from './Axios';
import { getToken } from '/@/utils/auth';
import { AxiosTransform } from './axiosTransform';
import { checkStatus } from './checkStatus';
@@ -16,11 +14,12 @@
import { RequestEnum, ResultEnum, ContentTypeEnum } from '/@/enums/httpEnum';
import { isString } from '/@/utils/is';
import { formatRequestDate } from '/@/utils/dateUtil';
import { setObjToUrlParams, deepMerge } from '/@/utils';
import { errorStore } from '/@/store/modules/error';
import { errorResult } from './const';
import { useI18n } from '/@/hooks/web/useI18n';
import { createNow, formatRequestDate } from './helper';
import { userStore } from '/@/store/modules/user';
const globSetting = useGlobSetting();
const prefix = globSetting.urlPrefix;
@@ -97,7 +96,7 @@
  // 请求之前处理config
  beforeRequestHook: (config, options) => {
    const { apiUrl, joinPrefix, joinParamsToUrl, formatDate } = options;
    const { apiUrl, joinPrefix, joinParamsToUrl, formatDate, joinTime = true } = options;
    if (joinPrefix) {
      config.url = `${prefix}${config.url}`;
@@ -106,31 +105,27 @@
    if (apiUrl && isString(apiUrl)) {
      config.url = `${apiUrl}${config.url}`;
    }
    if (config.method === RequestEnum.GET) {
      const now = new Date().getTime();
      if (!isString(config.params)) {
        config.data = {
          // 给 get 请求加上时间戳参数,避免从缓存中拿数据。
          params: Object.assign(config.params || {}, {
            _t: now,
          }),
        };
    const params = config.params || {};
    if (config.method?.toUpperCase() === RequestEnum.GET) {
      if (!isString(params)) {
        // 给 get 请求加上时间戳参数,避免从缓存中拿数据。
        config.params = Object.assign(params || {}, createNow(joinTime, false));
      } else {
        // 兼容restful风格
        config.url = config.url + config.params + `?_t=${now}`;
        config.url = config.url + params + `${createNow(joinTime, true)}`;
        config.params = undefined;
      }
    } else {
      if (!isString(config.params)) {
        formatDate && formatRequestDate(config.params);
        config.data = config.params;
      if (!isString(params)) {
        formatDate && formatRequestDate(params);
        config.data = params;
        config.params = undefined;
        if (joinParamsToUrl) {
          config.url = setObjToUrlParams(config.url as string, config.data);
        }
      } else {
        // 兼容restful风格
        config.url = config.url + config.params;
        config.url = config.url + params;
        config.params = undefined;
      }
    }
@@ -142,7 +137,7 @@
   */
  requestInterceptors: (config) => {
    // 请求之前处理config
    const token = getToken();
    const token = userStore.getTokenState;
    if (token) {
      // jwt token
      config.headers.Authorization = token;
@@ -157,14 +152,13 @@
    const { t } = useI18n();
    errorStore.setupErrorHandle(error);
    const { response, code, message } = error || {};
    const msg: string =
      response && response.data && response.data.error ? response.data.error.message : '';
    const err: string = error.toString();
    const msg: string = response?.data?.error?.message ?? '';
    const err: string = error?.toString?.() ?? '';
    try {
      if (code === 'ECONNABORTED' && message.indexOf('timeout') !== -1) {
        createMessage.error(t('sys.api.apiTimeoutMessage'));
      }
      if (err && err.includes('Network Error')) {
      if (err?.includes('Network Error')) {
        createErrorModal({
          title: t('sys.api.networkException'),
          content: t('sys.api.networkExceptionMsg'),
@@ -173,7 +167,7 @@
    } catch (error) {
      throw new Error(error);
    }
    checkStatus(error.response && error.response.status, msg);
    checkStatus(error?.response?.status, msg);
    return Promise.reject(error);
  },
};
@@ -188,6 +182,8 @@
        // 接口可能会有通用的地址部分,可以统一抽取出来
        prefixUrl: prefix,
        headers: { 'Content-Type': ContentTypeEnum.JSON },
        // 如果是form-data格式
        // headers: { 'Content-Type': ContentTypeEnum.FORM_URLENCODED },
        // 数据处理方式
        transform,
        // 配置项,下面的选项都可以在独立的接口请求中覆盖
@@ -204,6 +200,8 @@
          errorMessageMode: 'message',
          // 接口地址
          apiUrl: globSetting.apiUrl,
          //  是否加入时间戳
          joinTime: true,
        },
      },
      opt || {}