• 【axios网络请求库】认识Axios库;axios发送请求、创建实例、创建拦截器、封装请求


    1_认识Axios库

    功能特点:

    • 在浏览器中发送 XMLHttpRequests 请求
    • 在 node.js 中发送 http请求
    • 支持 Promise API
    • 拦截请求和响应
    • 转换请求和响应数据

    2_axios发送请求

    支持多种请求方式:

    • axios(config)
    • axios.request(config)
    • axios.get(url[, config])
    • axios.delete(url[, config])
    • axios.head(url[, config])
    • axios.post(url[, data[, config]])
    • axios.put(url[, data[, config]])
    • axios.patch(url[, data[, config]])

    有时候, 可能需求同时发送两个请求

    • 使用axios.all, 可以放入多个请求的数组.
    • axios.all([]) 返回的结果是一个数组,使用 axios.spread 可将数组 [res1,res2] 展开为 res1, res2

    常见的配置选项

    (前三个选项常用)

    • 请求地址 url: ‘/user’,

    • 请求类型 method: ‘get’,

    • 请求根路径 baseURL: ‘http://www.mt.com/api’,

    • 请求前的数据处理 transformRequest:[function(data){}],

    • 请求后的数据处理 transformResponse: [function(data){}],

    • 自定义的请求头 headers:{‘x-Requested-With’:‘XMLHttpRequest’},

    • URL查询对象 params:{ id: 12 }

    • 查询对象序列化函数 paramsSerializer: function(params){ }

    • request body为 data: { key: ‘aa’},

    • 超时设置 timeout: 1000,

    demo1

    // 1.发送request请求
    axios.request({
      url: "http://123.207.32.32:8000/home/multidata",
      method: "get"
    }).then(res => {
      console.log("res:", res.data)
    })
    
    // 2.发送get请求
    axios.get(`http://123.207.32.32:9001/lyric?id=500665346`).then(res => {
      console.log("res:", res.data.lrc)
    })
    axios.get("http://123.207.32.32:9001/lyric", {
      params: {
        id: 500665346
      }
    }).then(res => {
      console.log("res:", res.data.lrc)
    })
    
    
    // 3.发送post请求
    axios.post("http://123.207.32.32:1888/02_param/postjson", {
      data: {
        name: "coderwhy",
        password: 123456
      }
    }).then(res => {
      console.log("res", res.data)
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30

    demo2

    // 1.baseURL
    const baseURL = "http://123.207.32.32:8000"
    
    // 给axios实例配置公共的基础配置
    axios.defaults.baseURL = baseURL
    axios.defaults.timeout = 10000
    axios.defaults.headers = {}
    
    // 1.get: /home/multidata
    axios.get("/home/multidata").then(res => {
      console.log("res:", res.data)
    })
    
    
    
    // 2.axios发送多个请求
    // Promise.all
    axios.all([
      axios.get("/home/multidata"),
      axios.get("http://123.207.32.32:9001/lyric?id=500665346")
    ]).then(res => {
      console.log("res:", res)
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    3_axios创建实例

    从axios模块中导入对象时, 使用的实例是默认的实例;

    • 当给该实例设置一些默认配置时, 这些配置就被固定下来了.
    • 但是后续开发中, 某些配置可能会不太一样;
    • 比如某些请求需要使用特定的baseURL或者timeout等.
    • 这时,就可以创建新的实例, 并且传入属于该实例的配置信息
    
    // axios默认库提供实例对象
    axios.get("http://123.207.32.32:9001/lyric?id=500665346")
    
    // 创建其他的实例发送网络请求
    const instance1 = axios.create({
      baseURL: "http://123.207.32.32:9001",
      timeout: 6000,
      headers: {}
    })
    
    instance1.get("/lyric", {
      params: {
        id: 500665346
      }
    }).then(res => {
      console.log("res:", res.data)
    })
    
    const instance2 = axios.create({
      baseURL: "http://123.207.32.32:8000",
      timeout: 10000,
      headers: {}
    })
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25



    4_axios的拦截器

    axios的也可以设置拦截器:拦截每次请求和响应

    • axios.interceptors.request.use(请求成功拦截, 请求失败拦截)
    • axios.interceptors.response.use(响应成功拦截, 响应失败拦截)

    demo

    // 对实例配置拦截器
    //【请求】
    axios.interceptors.request.use((config) => {
      console.log("请求成功的拦截")
      // 1.开始loading的动画
    
      // 2.对原来的配置进行一些修改
      // 2.1. header
      // 2.2. 认证登录: token/cookie
      // 2.3. 请求参数进行某些转化
    
      return config
    }, (err) => {
      console.log("请求失败的拦截")
      return err
    })
    //【响应】
    axios.interceptors.response.use((res) => {
      console.log("响应成功的拦截")
    
      // 1.结束loading的动画
    
      // 2.对数据进行转化, 再返回数据
      return res.data
    }, (err) => {
      console.log("响应失败的拦截:", err)
      return err
    })
    
    axios.get("http://123.207.32.32:9001/lyric?id=500665346").then(res => {
      console.log("res:", res)
    }).catch(err => {
      console.log("err:", err)
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34

    5_axios请求封装

    便于以后突发情况,比如axios库不再维护

    import axios from 'axios'
    
    class HYRequest {
      constructor(baseURL, timeout=10000) {
        this.instance = axios.create({
          baseURL,
          timeout
        })
      }
    
      request(config) {
        return new Promise((resolve, reject) => {
          this.instance.request(config).then(res => {
            resolve(res.data)
          }).catch(err => {
            reject(err)
          })
        })
      }
    
      get(config) {
        return this.request({ ...config, method: "get" })
      }
    
      post(config) {
        return this.request({ ...config, method: "post" })
      }
    }
    
    export default new HYRequest("http://123.207.32.32:9001")
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30




















































































































  • 相关阅读:
    产品渲染3D效果图一张多少钱,哪个平台更有性价比?
    业务数据分析-Excel数据透视表(四)
    (搞定)排序数据结构(1)插入排序 选择排序+冒泡排序
    银行软件测试:基于互联网金融平台的测试框架设计与分析
    .Net之接口小知识
    通用分页(1)
    docker数据管理
    CocosCreator3.8研究笔记(十)CocosCreator 图像资源的理解
    MySQL 中读写分离数据延迟
    鸿蒙布局List简介
  • 原文地址:https://blog.csdn.net/qq_54075517/article/details/132575468