• axios从入门到源码分析之axios的理解和使用(一)


    ⭐️⭐️⭐️  作者:船长在船上
    🚩🚩🚩  主页:来访地址船长在船上的博客
    🔨🔨🔨  简介:资深前端开发工程师,专注前端开发,欢迎咨询交流,共同学习

    🔔🔔🔔   感谢:如果觉得博主的文章不错或者对你的工作有帮助或者解决了你的问题,可以关注、支持一下博主,如果三连收藏支持就会更好,在这里博主不胜感激!!!如有疑问可以留言、评论,看到后会及时回复。  
     

    axios从入门到源码分析

    1章:axios的理解和使用

    1.1.axios是什么?

    • 前端最流行的ajax请求库
    • react/vue官方都推荐使用axiosajax请求
    • 文档: https://github.com/axios/axios

    1.2.axios特点

    • 基于 xhr + promise 的异步 ajax 请求库
    • 浏览器端/node 端都可以使用
    • 支持请求/响应拦截器
    • 支持请求取消
    • 请求/响应数据转换
    • 批量发送多个请求

    1.3. axios 常用语法

    • axios(config): 通用/最本质的发任意类型请求的方式
    • axios(url[, config]): 可以只指定 url 发 get 请求
    • axios.request(config): 等同于 axios(config)
    • axios.get(url[, config]): 发 get 请求
    • axios.delete(url[, config]): 发 delete 请求
    • axios.post(url[, data, config]): 发 post 请求
    • axios.put(url[, data, config]): 发 put 请求

    • axios.defaults.xxx: 请求的默认全局配置
    • axios.interceptors.request.use(): 添加请求拦截器
    • axios.interceptors.response.use(): 添加响应拦截器
    • axios.create([config]): 创建一个新的 axios(它没有下面的功能)
    • axios.Cancel(): 用于创建取消请求的错误对象
    • axios.CancelToken(): 用于创建取消请求的 token 对象
    • axios.isCancel(): 是否是一个取消请求的错误
    • axios.all(promises): 用于批量执行多个异步请求
    • axios.spread(): 用来指定接收所有成功数据的回调函数的方法

    1. html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    6. <meta http-equiv="X-UA-Compatible" content="ie=edge">
    7. <title>axios基本使用title>
    8. <link crossorigin="anonymous" href="https://cdn.bootcss.com/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    9. <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js">script>
    10. head>
    11. <body>
    12. <div class="container">
    13. <h2 class="page-header">基本使用h2>
    14. <button class="btn btn-primary"> 发送GET请求 button>
    15. <button class="btn btn-warning" > 发送POST请求 button>
    16. <button class="btn btn-success"> 发送 PUT 请求 button>
    17. <button class="btn btn-danger"> 发送 DELETE 请求 button>
    18. div>
    19. <script>
    20. //获取按钮
    21. const btns = document.querySelectorAll('button');
    22. //第一个
    23. btns[0].onclick = function(){
    24. //发送 AJAX 请求
    25. axios({
    26. //请求类型
    27. method: 'GET',
    28. //URL
    29. url: 'http://localhost:3000/posts/2',
    30. }).then(response => {
    31. console.log(response);
    32. });
    33. }
    34. //添加一篇新的文章
    35. btns[1].onclick = function(){
    36. //发送 AJAX 请求
    37. axios({
    38. //请求类型
    39. method: 'POST',
    40. //URL
    41. url: 'http://localhost:3000/posts',
    42. //设置请求体
    43. data: {
    44. title: "今天天气不错, 还挺风和日丽的",
    45. author: "张三"
    46. }
    47. }).then(response => {
    48. console.log(response);
    49. });
    50. }
    51. //更新数据
    52. btns[2].onclick = function(){
    53. //发送 AJAX 请求
    54. axios({
    55. //请求类型
    56. method: 'PUT',
    57. //URL
    58. url: 'http://localhost:3000/posts/3',
    59. //设置请求体
    60. data: {
    61. title: "今天天气不错, 还挺风和日丽的",
    62. author: "李四"
    63. }
    64. }).then(response => {
    65. console.log(response);
    66. });
    67. }
    68. //删除数据
    69. btns[3].onclick = function(){
    70. //发送 AJAX 请求
    71. axios({
    72. //请求类型
    73. method: 'delete',
    74. //URL
    75. url: 'http://localhost:3000/posts/3',
    76. }).then(response => {
    77. console.log(response);
    78. });
    79. }
    80. script>
    81. body>
    82. html>

    1.4. 难点语法的理解和使用  

    1.4.1. axios.create(config)

    1.根据指定配置创建一个新的 axios, 也就就每个新 axios 都有自己的配置

    2.新 axios 只是没有取消请求和批量发请求的方法, 其它所有语法都是一致的

    3.为什么要设计这个语法?

    (1) 需求 : 项目中有部分接口需要的配置与另一部分接口需要的配置不太一
    , 如何处理
    (2) 解决 : 创建 2 个新 axios, 每个都有自己特有的配置 , 分别应用到不同要
    求的接口请求中
    拦截器函数/ajax 请求/请求的回调函数的调用顺序

    1. 说明: 调用 axios()并不是立即发送 ajax 请求, 而是需要经历一个较长的流程

    2. 流程: 请求拦截器2 => 请求拦截器1 => ajax请求 => 响应拦截器1 =>

    应拦截器 2 => 请求的回调

    3. 注意: 此流程是通过 promise 串连起来的, 请求拦截器传递的是 config, 响应

    拦截器传递的是 response

    1. html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    6. <title>拦截器title>
    7. <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js">script>
    8. head>
    9. <body>
    10. <script>
    11. // Promise
    12. // 设置请求拦截器 config 配置对象
    13. axios.interceptors.request.use(function (config) {
    14. console.log('请求拦截器 成功 - 1号');
    15. //修改 config 中的参数
    16. config.params = {a:100};
    17. return config;
    18. }, function (error) {
    19. console.log('请求拦截器 失败 - 1号');
    20. return Promise.reject(error);
    21. });
    22. axios.interceptors.request.use(function (config) {
    23. console.log('请求拦截器 成功 - 2号');
    24. //修改 config 中的参数
    25. config.timeout = 2000;
    26. return config;
    27. }, function (error) {
    28. console.log('请求拦截器 失败 - 2号');
    29. return Promise.reject(error);
    30. });
    31. // 设置响应拦截器
    32. axios.interceptors.response.use(function (response) {
    33. console.log('响应拦截器 成功 1号');
    34. return response.data;
    35. // return response;
    36. }, function (error) {
    37. console.log('响应拦截器 失败 1号')
    38. return Promise.reject(error);
    39. });
    40. axios.interceptors.response.use(function (response) {
    41. console.log('响应拦截器 成功 2号')
    42. return response;
    43. }, function (error) {
    44. console.log('响应拦截器 失败 2号')
    45. return Promise.reject(error);
    46. });
    47. //发送请求
    48. axios({
    49. method: 'GET',
    50. url: 'http://localhost:3000/posts'
    51. }).then(response => {
    52. console.log('自定义回调处理成功的结果');
    53. console.log(response);
    54. });
    55. script>
    56. body>
    57. html>

    1.4.2. 取消请求

    1. 基本流程

    • 配置 cancelToken 对象
    • 缓存用于取消请求的 cancel 函数
    • 在后面特定时机调用 cancel 函数取消请求
    • 在错误回调中判断如果 error cancel, 做相应处理

    2. 实现功能

    • 点击按钮, 取消某个正在请求中的请求
    • 在请求一个接口前, 取消前面一个未完成的请求
    1. html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    6. <title>取消请求title>
    7. <link crossorigin='anonymous' href="https://cdn.bootcss.com/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    8. <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js">script>
    9. head>
    10. <body>
    11. <div class="container">
    12. <h2 class="page-header">axios取消请求h2>
    13. <button class="btn btn-primary"> 发送请求 button>
    14. <button class="btn btn-warning" > 取消请求 button>
    15. div>
    16. <script>
    17. //获取按钮
    18. const btns = document.querySelectorAll('button');
    19. //2.声明全局变量
    20. let cancel = null;
    21. //发送请求
    22. btns[0].onclick = function(){
    23. //检测上一次的请求是否已经完成
    24. if(cancel !== null){
    25. //取消上一次的请求
    26. cancel();
    27. }
    28. axios({
    29. method: 'GET',
    30. url: 'http://localhost:3000/posts',
    31. //1. 添加配置对象的属性
    32. cancelToken: new axios.CancelToken(function(c){
    33. //3. 将 c 的值赋值给 cancel
    34. cancel = c;
    35. })
    36. }).then(response => {
    37. console.log(response);
    38. //将 cancel 的值初始化
    39. cancel = null;
    40. })
    41. }
    42. //绑定第二个事件取消请求
    43. btns[1].onclick = function(){
    44. cancel();
    45. }
    46. script>
    47. body>
    48. html>

    下一篇文章:

       👉👉👉 欢迎来访船长在船上的博客,如有疑问可以留言、评论,看到后会及时回复。  

  • 相关阅读:
    梯度消失和梯度爆炸问题详解
    Numpy字符串数组总结
    C Primer Plus(6) 中文版 第6章 C控制语句:循环 6.3 用关系运算符和表达式比较大小
    夯实C++基础学习笔记
    手机实时预览vscode写的html页面
    9 JDBC
    centos搭建yum本地源
    【On Nacos】快速上手 Nacos
    Redis集群模式
    关于使用VNC Viewer连接Ubuntu教程
  • 原文地址:https://blog.csdn.net/SmartJunTao/article/details/126259451