axios 封装基础请求库

本文介绍了一个基于Vue.js和Axios的HTTP请求库的封装实践,包括配置不同基础请求地址、接口请求loading管理、token处理、参数过滤与trim、错误提示及统一封装post、get请求等。通过设置拦截器实现了请求和响应的处理,如自动显示加载、错误提示和接口错误处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

axios  封装基础请求库,简化接口请求代码。提供以下功能

1、配置不同基础请求地址

2、接口请求loading

3、附带token

4、处理token过期

5、自动过滤参数中null、undefined、''、[]参数

6、自动trim一些字符串参数

7、接口错误自动提示

8、统一post、get请求参数传递,不同像axios那样去区分params、data

import axios from 'axios';
import { ElMessage, ElLoading } from 'element-plus';
import { useRouter } from 'vue-router';
import appConfig from '../config';

const router = useRouter();
// 通过识别路由前缀分别代理到不同的服务器
axios.defaults.headers['content-type'] = 'application/json';
axios.defaults.timeout = 50000;
export default class Request {
  loading // loading 实例

  instance // axios 实例

  constructor(cfg = {}) {
    const baseUrl = cfg.baseUrl || 'apiGateway';
    this.instance = axios.create({
      baseURL: appConfig.gateway[baseUrl],
    });
    this.setInterceptors();
  }

  /**
   * get 请求
   * @param {string} url 请求地址
   * @param {json} param 参数
   * @param {json} config 配置,同post
   * @returns promise
   */
  get(url, param = {}, config) {
    return this.instance.request({
      method: 'post',
      url,
      params: param,
      config,
    });
  }

  /**
   * post 请求
   * @param {string} url 请求地址
   * @param {json} param 参数,网关要求,空参数也要{}
   * @param {json} config 配置
   *  {
   *    showLoading: true,  // 是否显示loading,默认为true
   *    autoShowError: true // 非200的是否自动显示错误,默认为true
   *    autoFilterParam:true // 自动过滤掉参数中的值为null的参数,默认为true
   *    autoTrim: true // 默认过滤字符串参数中两边空格,默认为true,
   *    needToken : true // 是否需要携带token,默认为true
   *  }
   * @returns promise
   */
  post(url, param = {}, config) {
    return this.instance.request({
      method: 'post',
      url,
      data: param,
      config,
    });
  }

  // 排除无用参数目前只过滤null、undefined、''、[],只过滤一层数据
  static filterParam(params) {
    if (params) {
      const keys = Object.keys(params);
      keys.forEach((key) => {
        const item = params[key];
        if (item === null || item === undefined || item === '' || (item instanceof Array && item.length === 0)) {
          // eslint-disable-next-line no-param-reassign
          delete params[key];
        }
      });
    }
  }

  // 去除字符串参数两边空格
  static autoTrimParam(params) {
    if (params) {
      const keys = Object.keys(params);
      keys.forEach((key) => {
        const item = params[key];
        if (typeof item === 'string') {
          // eslint-disable-next-line no-param-reassign
          params[key] = item.trim();
        }
      });
    }
  }

  // 添加拦截器
  setInterceptors() {
    this.setInterceptorsRequest();
    this.setInterceptorsResponse();
  }

  // 添加请求拦截器
  setInterceptorsRequest() {
    this.instance.interceptors.request.use((config) => {
      const newConfig = { ...config };

      // 赋配置默认值
      if (!newConfig.config) {
        newConfig.config = {
          showLoading: true,
          autoShowError: true,
          autoFilterParam: true,
          autoTrim: true,
          needToken: true,
        };
      } else {
        const {
          showLoading = true,
          autoShowError = true,
          autoFilterParam = true,
          autoTrim = true,
          needToken = true,
        } = newConfig.config;

        newConfig.config = {
          showLoading, autoShowError, autoFilterParam, autoTrim, needToken,
        };
      }

      const consumerConfig = newConfig.config;

      if (consumerConfig.showLoading) {
        this.loading = ElLoading.service({
          lock: true,
          text: '加载中...',
          background: 'rgba(255, 255, 255, 0)',
        });
      }
      const token = sessionStorage.getItem('token');
      if (consumerConfig.needToken && token) {
        newConfig.headers['mall-platform-authorization'] = `Bearer ${token}`;
      }

      if (consumerConfig.autoTrim) {
        Request.autoTrimParam(newConfig.data);
        Request.autoTrimParam(newConfig.params);
      }
      if (consumerConfig.autoFilterParam) {
        Request.filterParam(newConfig.data);
        Request.filterParam(newConfig.params);
      }

      return newConfig;
    }, (error) => {
      if (this.loading) {
        this.loading.close();
      }

      ElMessage.error('客户端请求异常,请稍后重试!');
      return Promise.reject(error);
    });
  }

  // 添加响应拦截器
  setInterceptorsResponse() {
    this.instance.interceptors.response.use((response) => {
      if (response) {
        const res = response.data;
        if (this.loading) {
          this.loading.close();
        }
        if (res && res.code === 401) {
          router.push('/login');
          return;
        }

        if (response.config) {
          const { config } = response.config;
          // 非200提示错误
          if (res && res.code !== 200 && config && config.autoShowError) {
            ElMessage.error(`code:${res.status}:${res.message}`);
          }
        }

        return res;
      }
    }, (error) => {
      if (this.loading) {
        this.loading.close();
      }
      ElMessage.error(error.response.data);
      return Promise.reject(error);
    });
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值