Axios-精解-方式-拦截

Axios

特性

  1. 支持node端和浏览器端
  2. promise
  3. 丰富的配置项
    1. transformRequest
    2. transformResponse
    3. baseURL
    4. 拦截器
  4. 社区庞大

安装

 npm i axios

使用

npm

// 哪个地方用得到就在哪个组件引入
  import Axios from 'axios'

CDN

常用方法

基本用法

axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});

get

axios.get('/user', {
    params: {
      ID: 12345
    }
})

post

axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
})

All
多个请求,全部成功了,才算成功;有一个失败了,就算失败了

// 第一个接口
function getCnode() {
    return Axios.get('https://cnodejs.org/api/v1/topics111');
}
// 第二个接口
function getMall() {
    return Axios.get('https://api.it120.cc/small4/shop/goods/category/all');
}
​
// 并发请求
Axios.all([getCnode(), getMall()])
    .then( (res1, res2) => {
    // 两个请求现在都执行完成
    console.log(res1)
    console.log(res2)
}))
    .catch(err => {
    console.log(err)
})

Race - 赛跑,比谁跑得快
多个接口,只要有一个成功了,就算成功

// 第一个接口
function getCnode() {
    return Axios.get('https://cnodejs.org/api/v1/topics111');
}
// 第二个接口
function getMall() {
    return Axios.get('https://api.it120.cc/small4/shop/goods/category/all');
}
​
// 并发请求
Axios.race([getCnode(), getMall()])
    .then(( (res1, res2) => {
    // 两个请求现在都执行完成
    console.log(res1)
    console.log(res2)
}))
    .catch(err => {
    console.log(err)
})

Spread() - 处理并发请求的便于取值的函数

// 第一个接口
function getCnode() {
    return Axios.get('https://cnodejs.org/api/v1/topics111');
}
// 第二个接口
function getMall() {
    return Axios.get('https://api.it120.cc/small4/shop/goods/category/all');
}
​
// 并发请求
Axios.all([getCnode(), getMall()])
    .then(Axios.spread(function (res1, res2) {
    // 两个请求现在都执行完成
    console.log(res1)
    console.log(res2)
}))
    .catch(err => {
    console.log(err)
})

拦截器

拦截器,顾名思义,用来拦截什么东西的
在Axios中拦截器是用来拦截ajax请求的
分两组共有四个拦截点

  1. request

    成功
    失败

  2. response

      成功
      失败
    

实战案例 - loading动画

 // App.vue
  <template>
    <div style="position: fixed; top: 0; left: 0; background: orange; opacity: 0.5; width: 100%; height: 1000px; text-align:center; padding-top: 420px; font-size: 100px;" v-show="isLoading">Loading...</div>    
  </template>
  export default {
      data() {
          return {
              isLoading: true // 默认显示
          }
      },
      created () {
          // 添加响应拦截器
          Axios.interceptors.response.use( (response) => {
              // 对响应数据做点什么
              this.isLoading = false // 数据请求成功isloading改为false,loading隐藏掉
              return response;
          });
      }
  }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值