王云飞给小菜鸡儿的Axios详解教程

1 篇文章 0 订阅

Axios

Axios是什么?

Axios 是一个基于 promise 的 HTTP 库。

特性

  • 支持node端和浏览器端
  • 支持promise
  • 丰富的配置项
    • headers
    • transformRequest
    • transformResponse
    • baseURL
    • 拦截器
  • 提供了一些并发请求的方法
  • 社区庞大,增长速度快

基本用法

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

get

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

post

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

基本配置,比较好理解,没什么可说的

baseURL: 'https://api.it120.cc/small4/', // 默认地址前缀,自动加载请求API的前面
timeout: 10000, // // `timeout` 指定请求超时的毫秒数(0 表示无超时时间);如果请求话费了超过 `timeout` 的时间,请求将被中断
headers: { // 自定义的请求头,常见场景就是发送token进行鉴权
    'custom-header': 'wyunfei',
    'content-type': 'application/x-www-form-urlencoded' // 转为&连接的形式
}

transformRequest

// Axios实例
transformRequest: [function (data) { // 允许在向服务器发送请求前,修改请求数据
    data.position ='FrontEnd' // 只能用在 'PUT', 'POST' 和 'PATCH' 这几个请求方法;且必须在请求API的时候传参,否则无效(Cannot set property 'FrontEnd' of undefined)
    return queryString.stringify(data) // 必须返回一个字符串
}]
// 请求API
created() {
    HTTP.post('shop/goods/category/all', {
        nickName: 'SmallFour'
    })
}

王云飞-小四

transformReponse

// Axios实例
transformResponse: [function (data) {  // 对返回数据进行处理
    let sf = (JSON.parse(data))
    sf.name = '王云飞' // 在API中添加字段
    return sf
}]
// 请求API
created() {
    HTTP.post('shop/goods/category/all', {
        nickName: 'SmallFour'
    }).then(res  => {
        console.log(res)
    })
}

王云飞

validateStatus

// Axios实例
validateStatus (status) {
    console.log(status)
    console.log(status < 405)
    return status > 405 //状态码大于405时均为成功(返回true);status < 405均为失败,即便是状态码200了,axios依旧会失败;
}
// API请求
created() {
    HTTP.post('shop/goods/category/all', {
        nickName: 'SmallFour'
    }).then(res  => {
        console.log(res)
    }).catch(err => {
        console.log(err) // 状态码200:,但是axios依旧返回了错,因为validateStatus:200 < 405 返回false
    })
}

王云飞

并发请求及取值

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请求的

分两组共有四个拦截点

  • request

    • 成功

    • 失败

  • 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;
          });
      }
  }

Axios、fetch、ajax(jquery)区别

  • 前两者支持promise,后者默认是用callback方式
  • fetch本质上脱离了xhr,是新的语法(有自己的特性,默认不支持cookie,不能像xhr一样去监听请求的进度)

描述使用axios实现登录的流程

登录基本流程描述

客户端用户输入账户密码通过API传递给后台,后台收到账户和密码以后就会和数据库中的进行比对,如果都正确,那么就更新用户的状态为已登录。

axios登录和其它最大的区别

就是提供了拦截器功能

王云飞@小四版权logo,转载记得一起带走哦!!!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值