网络模块封装 - axios

1. axios框架的基本使用

  • 一般在main.js中全局配置

  • url中写入后端数据地址,就能获取到想要的数据

    import axios from 'axios'
    
    axios({
      url: 'http://123.207.32.32:8000/home/multidata'
    }).then(res => {
      console.log(res);
    })
    
    // 有请求参数的
    axios({
      url: 'http://123.207.32.32:8000/home/data',
      params:{
        type: 'sell',
        page: 5
      }
    }).then(res => {
      console.log(res);
    })
    

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ecevCxhk-1631243449053)(C:\Users\xmydd\AppData\Roaming\Typora\typora-user-images\image-20210909163658805.png)]

1.1 get请求

需要发送get请求,就是axios.get()

axios.get('http://123.207.32.32:8000/home/multidata')
    .then(res => {console.log(res)})
    .catch(err => {console.log(err)})
  • 有请求参数的
axios.get('http://123.207.32.32:8000/home/multidata',{params:{type:'sell', page: 1}})
    .then(res => {console.log(res)})
    .catch(err => {console.log(err)})
1.2 post请求
  • post请求 - axios.post()

    • 没有参数的
    axios.post('http://123.207.32.32:8000/home/multidata')
        .then(res => {console.log(res)})
        .catch(err => {console.log(err)})
    
    • 有参数的
    axios.post('http://123.207.32.32:8000/home/multidata',{data:{key:'sell'})
        .then(res => {console.log(res)})
        .catch(err => {console.log(err)})
    
1.3 axios发送并发请求
  • 有时候,我们可能需求同时发送两个请求

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

    axios.all([axios({
      url:'http://123.207.32.32:8000/home/multidata',
    }), axios({
      url: 'http://123.207.32.32:8000/home/data',
      params:{
        type: 'sell',
        page: 5
      }
    })]).then(res => {
      console.log(res);
    })
    
  • 使用了axios.spread

    axios.all([axios({
      url:'http://123.207.32.32:8000/home/multidata',
    }), axios({
      url: 'http://123.207.32.32:8000/home/data',
      params:{
        type: 'sell',
        page: 5
      }
    })]).then(axios.spread((res1, res2) => {
      console.log(res1);
      console.log(res2);
    }))
    

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-OnOBD9v1-1631243449059)(C:\Users\xmydd\AppData\Roaming\Typora\typora-user-images\image-20210909163114104.png)]

2. axios实例和模块封装

  • 当所有的请求路径只有最后一部分不同时,我们可以给相同的地方配置全局路径

    // 配置根路径
    axios.defaults.baseUrl = 'http://123.207.32.32:8000'
    // 配置全局超时时间
    axios.defaults.timeout = 5000
    
    • 需要具体请求那个路径时,只需要用url进行拼接
    axios.all([axios({
      url:'/home/multidata',
    })
    
  • 但是,如果有的请求路径根目录不一样,就不能配置全局根路径。

    • 我们可以创建axios实例,并对它进行封装
2.1 封装
  • 在src目录下新建文件夹network,新建文件request.js

  • request.js

    import axios from 'axios'
    
    export function request(config){
        const instance = axios.create({
            baseURL: 'http://123.207.32.32:8000',
            timeout: 1000
        });
    
        // 发送请求
        return instance(config);
    }
    
2.1.1 解析

上面的代码是最终呈现的效果,我们来解释一下为什么要这么写。

  • 第一步,封装一个函数request并且通过export将其导出,这个没什么好解释的,我们要是想在其他组件或js文件中使用就必须这样导出。

  • 第二部,通过axios.create创建axios实例instance,在里面传入我们需要的数据

    • 查看axios.create的源码我们可以知道,除了上面的baseURLtimeout以外,我们还没传入其他想要的属性(截图只是一部分)
      [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ZrKWIlFh-1631243449062)(C:\Users\xmydd\AppData\Roaming\Typora\typora-user-images\image-20210909214846777.png)][外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-zhNgibbL-1631243449071)(C:\Users\xmydd\AppData\Roaming\Typora\typora-user-images\image-20210909215032509.png)]
  • 第三步,接收传过来的参数config,处理数据得到结果

    • 用创建的实例对象instance接收传过来的参数

    • 我们不能在request.js中接收得到的结果,所以需要将结果返回给调用了这个方法的文件,让他来接收处理。

    • 我们可以通过Promise将的到的结果返回出去

      export function request(config){
          return new Promise((resolve, reject) => {
              const instance = axios.create({
                  baseURL: 'http://123.207.32.32:8000',
                  timeout: 1000
              });
              console.log(config);
              // 发送请求
              instance(config)
                  .then(res => {
                      resolve(res);
                  })
                  .catch(err => {
                      reject(err);
                  })
          })
      }
      
      • 调用
      request({
        url:'/home/multidata'
      }, res => {
        console.log(res);
      },err => {
        console.log(err);
      })
      
    • 但是,我们通过查看源码可以知道,create创建的对象就是一个promise对象
      在这里插入图片描述

    • 所以我们直接返回创建的实例对象instance就可以了

      // 发送请求
      return instance(config);
      

3. axios拦截器的使用

  • 请求拦截器的实际应用场景
    • 在进行鉴权的时候;我们每个接口都需要携带token;
    • 难道每次我们都需要手动拼接token; 这个时候拦截器就很有用了;
    • 这时候就可以用拦截器来使token自动增加
      在这里插入图片描述
// 1. 请求拦截器
instance.interceptors.request.use(config => {
    //console.log(config);
    return config;
},err => {
    console.log(err);
});

// 2. 响应拦截
instance.interceptors.response.use(res => {
    //console.log(res);
    return res.data;
},err => {
    console.log(err);
});
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值