美文网首页
封装axios

封装axios

作者: Poppy11 | 来源:发表于2020-07-24 16:18 被阅读0次
    import axios, { AxiosBasicCredentials, AxiosError, AxiosInstance, AxiosRequestConfig, AxiosResponse, AxiosStatic } from 'axios';
    import { history } from 'umi';
    import { Toast } from 'antd-mobile';
    
    axios.defaults.timeout = 10000;
    axios.defaults.baseURL = 'http://47.96.172.194:8800/api';
    let requestCount = 0;
    
    function showLoading() {
      if (requestCount === 0) {
        Toast.show({ icon: 'loading', content: '加载中…', duration: 0, maskClickable: false });
      }
      requestCount++;
    }
    
    function hideLoading() {
      requestCount--;
      if (requestCount === 0) {
        Toast.clear();
      }
    }
    
    axios.interceptors.request.use(
      (config: AxiosRequestConfig) => {
        config.withCredentials = true;
        const token = localStorage.getItem('userToken');
        token && (config.headers['auth-token'] = `Bearer ${token}`);
        showLoading();
        return config;
      },
      (error) => {
        hideLoading();
        return Promise.reject(error);
      },
    );
    
    // 响应拦截器
    axios.interceptors.response.use(
      (response: AxiosResponse) => {
        hideLoading();
        if (response.status === 200) {
          switch (response.data.code) {
            case 200:
              return Promise.resolve(response);
            case 406:
              localStorage.clear();
              window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx54111bafe3d66199&redirect_uri=http%3A%2F%2F47.96.172.194%3A8800%2Fmobile%2Fhome&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';
              break;
            case 403:
              localStorage.clear();
              history.replace('/login');
              break;
            case 400 | 500:
              Toast.show({
                icon: 'fail',
                content: response.data.message,
              });
              break;
          }
          return Promise.reject(response);
        } else {
          Toast.clear();
          return Promise.reject(response);
        }
      },
      (error) => {
        if (error.response.status) {
          switch (error.response.status) {
            case 401:
              console.log('当状态码为401时操作');
              break;
            case 403:
              console.log('当状态码为403时操作');
              break;
            case 404:
              break;
            default:
              Toast.show({
                icon: 'fail',
                content: error.response.data.message,
              });
          }
          return Promise.reject(error.response);
        }
      },
    );
    
    // get
    export const get = (url: string, params?: any): any => {
      return new Promise((resolve, reject) => {
        axios
          .get(url, {
            params: { ...params },
          })
          .then((res) => {
            resolve(res.data);
          })
          .catch((error) => {
            reject(error.data);
          });
      });
    };
    
    // get
    export const deleteAxios = (url: string, params?: any): any => {
      return new Promise((resolve, reject) => {
        axios
          .delete(url, {
            params: { ...params },
          })
          .then((res) => {
            resolve(res.data);
          })
          .catch((error) => {
            reject(error.data);
          });
      });
    };
    
    // post
    export const post = (url: string, ...params: any) => {
      return new Promise((resolve, reject) => {
        axios
          .post(url, ...params)
          .then((res) => {
            resolve(res.data);
          })
          .catch((err) => {
            reject(err.data);
          });
      });
    };
    
    // put
    export const put = (url: string, ...params: any): any => {
      return new Promise((resolve, reject) => {
        axios
          .put(url, ...params)
          .then((res) => {
            resolve(res.data);
          })
          .catch((err) => {
            reject(err.data);
          });
      });
    };
    
    export const patch = (url: string, params: any) => {
      // 将数据转换为formData格式
      // 正常情况下可以直接使用参数对象进行patch,如果出错可以尝试转换form Data
      var formData = new FormData();
      formData.append('username', params.username);
      formData.append('password', params.password);
      return new Promise((resolve, reject) => {
        axios
          .patch(url, formData)
          .then((res) => {
            resolve(res.data);
          })
          .catch((err) => {
            reject(err.data);
          });
      });
    };
    
    

    相关文章

      网友评论

          本文标题:封装axios

          本文链接:https://www.haomeiwen.com/subject/imljlktx.html