通用 axios 封装处理,拿来即用

import axios from "axios";

const baseOptions = {};

const instance = axios.create(baseOptions);

// 用以控制请求的全局状态
const globalParams = {
  // 是否统一处理响应,
  // 1 ture,则返回响应,并根据http 错误状态码抛错
  // 2 false, 将响应或错误直接抛给调用者,调用者自行处理
  isUnified: true,
  isReturnData: true, // 是否值接返回response.data
  isLoading: false, // 是否有 loading 效果
  isCheckParams: false, // 检查用户输入是否存在违规内容, 比如 <script> </script> 等
};

// 从 config 向 global 合并属性
// 开发者在传递玩请求参数后边, 追加一个对象类型的参数, 配置相关属性即可
/**
 * 示例
 
   const onFinish =  async (values) => {
    console.log(values);
    const res = await req.post('/react/register', values, {
      isUnified : false
    })
    console.log(res);

  }

 */
const correspondWithConfig = (config) => {
  const keys = Object.keys(globalParams);
  keys.forEach((key) => {
    if (config.hasOwnProperty(key)) {
      globalParams[key] = config[key];
    }
  });
};

// 参数校验、检查逻辑
const checkParams = config => {

}

const handleConfig = (config) => {
  correspondWithConfig(config);
  checkParams(config)
};

// 注意查看 config 的属性
instance.interceptors.request.use(
  (config) => {
    handleConfig(config);
    console.log(config);
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 处理约定的业务代码
const handleBussnessCode = data => {

}
// 处理正常响应
const handleResponse = (res) => {

  const { isUnified, isLoading, isReturnData } = globalParams;
  if(isLoading) {
    // close loading
  }
  if(isUnified) {
    if(isReturnData) {
        // 统一处理响应
        return res.data
    }
    handleBussnessCode(res.data)
  }
  return res
};

const handleHTTPStatusCode = e => {

}

// 处理响应错误
const handleResponseError = e => {
    // The request was made and the server responded with a status code
    // that falls out of the range of 2xx
    if(e.response) {
        handleBussnessCode(e)
    }
    else if(e.request) {
    // The request was made but no response was received
    // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
    // http.ClientRequest in node.js

    }
    else {
    // Something happened in setting up the request that triggered an Error

    }
    // 其他错误
    return e

}

instance.interceptors.response.use(
    response =>  handleResponse(response),
    error => Promise.reject(handleResponseError(error))
);

export default instance;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值