使用 axios 封装请求类

对 axios 进行封装请求类

  1. 构建一个 Http 请求类
  2. 实现一个 request 的静态方法,传入参数,使用axios 发送请求
  3. 实现 requestExpection 构建失败对象的静态方法
  4. 实现一个判断结果是否成功的静态方法,如果成功就返回数据,如果失败就调用 requestExpection 这个方法
  5. 实现 get 、post 便携方法

示例代码呈上:

// 提供ajax请求
// 对axios进行二次封装
import axios from 'axios'
import {HOST} from './api'

export default class Http{

  static async request(method, url, data){
    // 发送请求
    const response = await axios.request({
      method,
      url,
      baseURL: HOST,
      params: method === 'GET' ? data : null,
      data: method === 'POST' ? data : null
    });
    // 判断是否成功
    return this.isSuccess(response);
  };

  // 判断响应结果是否成功
  static isSuccess(res){
    if(res.status >= 200 && res.status < 300){
      return res;
    }else{
      this.requestExpection(res);
    }
  };

  // 构建失败对象
  static requestExpection(res){
    throw new Error(res);
  };

  // get便捷方法
  static get(url, data){
    return this.request('GET', url, data);
  };

  // post便捷方法
  static post(url, data){
    return this.request('POST', url, data);
  }

}

// 实例方法   对象方法   arr.push()     this代表实例对象
// 静态方法   类方法    Array.from()   this代表类

今天好安静哦 ~

发布了22 篇原创文章 · 获赞 33 · 访问量 1202

猜你喜欢

转载自blog.csdn.net/weixin_44691775/article/details/104433225