前端学习笔记____axios从入门到源码分析

本文详述了axios的使用方法,包括GET、POST、PUT、DELETE等请求方式,以及如何通过json-server搭建模拟API。还介绍了axios的配置对象、默认配置、实例创建、拦截器和取消请求等功能,并探讨了axios的源码结构。
摘要由CSDN通过智能技术生成

🌵 作者主页:💖仙女不下凡💖

🌵 前言介绍:以下👇 内容都是我个人对于前端知识的总结,会定期更新欢迎持续关注!

🌵 欢迎点赞 👍 收藏 ⭐留言 📝 如有错误敬请指正!

🔥 视频地址:尚硅谷2021最新版axios入门与源码解析

🔥学习原因:axios是目前前端最热门的ajax请求,vuereact都用到了axios,面试时也经常涉及到这部分知识。


前置知识promise与ajax

json-server的介绍与服务搭建

json-server包可以快速搭建一个http服务,所以下面的所有代码请求的发动都是基于该http服务进行处理。
使用步骤:❶安装npm install -g json-server❷创建db.json文件❸用命令watch db.json启动服务。

/db.json文件内容如下/
{
  "posts":[{  //文章
    "id":1,
    "titile":"json-server",
    "author":"typecode"
  },{
    "id":2,
    "titile":"学习axios",
    "author":"项目"
  }],
  "comments":[{  //评论
    "id":1,
    "titile":"json-server",
    "author":"typecode"
  }],
  "profile":[{  //个人信息
    "name":"typecode",
    "titile":"json-server",
    "author":"typecode"
  }],
};

/启动服务后,会生成三个url /;
❶http://localhost:3000/posts
❷http://localhost:3000/comments
❸http://localhost:3000/profile
就可以调用里面的数据了/

axios安装

axios的安装两种方式❶使用命令行npm install axios安装❷页面直接引入,代码如下

<head>
  <script src="https://cd.jsodelivr.net/npm/axios/dist/axios.min.js"></script>
</head>

下面所有的示例代码都假设在已经安装axios的状态下,具体使用上述哪种方式请根据实际自行选择

axios的基本使用

<body>
  <div class="container">
      <button>发送GET请求</button>
      <button>发送POST请求</button>
      <button>发送PUT请求</button>
      <button>发送DELETE请求</button>
  </div>
  <script>
    const btns = document.querySelectorAll('button');
    btns[0].onclick = function(){
      axios({
        method: 'GET',
        url: 'http://localhost:3000/posts/2',
      }).then(response => { console.log(response) })
    };
    //添加一篇新的文章
    btns[1].onclick = function(){
      axios({
        method: 'POST',
        url: 'http://localhost:3000/posts',
        data: { title:"今天天气很好",author:"zhangsan" }
      }).then(response => (response => { console.log(response) })
    };
    //更新一篇文章
    btns[2].onclick = function(){
      axios({
        method: 'PUT',
        url: 'http://localhost:3000/posts/3',
        data: { title:"今天天气很好",author:"lisi" }
      }).then(response => (response => { console.log(response) })
    };
    //删除文章
    btns[2].onclick = function(){
      axios({
        method: 'DELETE',
        url: 'http://localhost:3000/posts/3'
      }).then(response => (response => { console.log(response) })
    };
  </script>
</body>

❶点击发送GET请求按钮后,db.json文件的内容不改变,执行结果为{id:2,titile:"学习axios",author:"项目"}
❷点击发送POST请求按钮后,将put请求中的请求体传给了服务器所以db.json文件的内容改变结构如下

"posts":[{ 
  "id":1,
  "titile":"json-server",
  "author":"typecode"
},{
  "id":2,
  "titile":"学习axios",
  "author":"项目"
},{
  "id":3,
  "titile":"今天天气很好",
  "author":"shangsan"
}]

❸点击发送PUT请求按钮后,改变了db.json文件中id为3的内容如下

"posts":[{ 
  "id":1,
  "titile":"json-server",
  "author":"typecode"
},{
  "id":2,
  "titile":"学习axios",
  "author":"项目"
},{
  "id":3,
  "titile":"今天天气很好",
  "author":"lisi"  //这里改变了
}]

❹点击发送DELETE请求按钮后,将db.json文件中id为3的内容删除如下

"posts":[{ 
  "id":1,
  "titile":"json-server",
  "author":"typecode"
},{
  "id":2,
  "titile":"学习axios",
  "author":"项目"
}]

axios其他方式发送请求

axios其他方式发送请求语法结构
axios.request(config)
axios.get(url [,config])
axios.delete(url [,config])
axios.head(url [,config])
axios.options(url [,config])
axios.post(url[, data [,config] ])
axios.delete(url[,data [,config] ])
axios.delete(url[, data[,config ] ])

除了用上述案例中axios()发送ajax请求以外也可以用axios上面的方法发送,下面我就用上述案例的代码举两个axios方法使用的栗子,其实和axios()含义是一样的会写就可以。示例代码如下

<body>
  <div class="container">
      <button>发送GET请求</button>
      <button>发送POST请求</button>
      <button>发送PUT请求</button>
      <button>发送DELETE请求</button>
  </div>
  <script>
    const btns = document.querySelectorAll('button');
    /演示axios.request()发送ajax请求/
    btns[0].onclick = function(){
      axios.request({
        method: 'GET',
        url: 'http://localhost:3000/posts/2',
      }).then(response => { console.log(response) })
    };
    /演示axios.post()发送ajax请求,添加一篇文章  注意这个写法不太一样/
    btns[1].onclick = function(){
      axios.post('http://localhost:3000/posts',{
        data: { title:"今天天气很好",author:"zhangsan" }
      }).then(response => (response => { console.log(response) })
    };
  </script>
</body>

axios请求响应结果的结构

在上述代码中console.log(response)执行结果为

/console.log(response)执行结果/
{
  config:{},  //配置对象, 请求类型,请求url,请求体
  data:{},  //响应体内容,就是服务器返回结果,axios将服务器返回结果自动json解析所以返回结果为json对象。
  headers:{},  //响应头信息
  request: XMLHTTPRequest{},  //是原生ajax请求对象
  status:200,  //响应状态码
  statusText:"OK",  //响应结果
  __proto__: object
}

axios配置对象config详细说明

{
  url: '/user',
  method: 'get',
  baseURL: 'http:localhost:3000',
  transformRequest: [function(data, headers){ return data }],  //对响应结果进行改变再返回预处理结果
  transformResponse: [function(data, headers){ return data }],  //对请求参数进行改变再发送
  headers: {'X-Requested-With': 'XMLHTTPRequest'},  //响应头信息
  params: {},  //请求参数
  paramsSerialiaer: function(params){},
  ......
}

axios的默认配置default

举几个栗子,其他的根据实际情况自行选择。

axios.default.method = 'GET';
axios.default.baseURL = http:localhost:3000;
axios.default.params = {id:100};
axios.default.timeout = 3000;  //超时时间

axios创建实例对象发送请求create()

<body>
  <div class="container">
      <button>发送GET请求</button>
      <button>发送POST请求</button>
  </div>
  <script>
    const btns = document.querySelectorAll('button');
    //创建实例对象 /getJoke
    const dunanzi = axios.create({
      baseURL: 'https://api.apiopen.top',
      timeout:2000
    });
    /这里duanzi与axios对象的功能几近是一样的, 但不是完全一样
    duanzi({
      url: '/getJoke',
    }).then(response => (response => { console.log(response) })
    /*还有另一种写法, 如下
    duanzi.get('/getJoke').then(response => (response => { console.log(response) })
    */
  </script>
</body>

优点:代码的复用率高。

axios拦截器

拦截器分为两类:请求拦截器响应拦截器
请求拦截器作用:在发送请求之前借助一些回调函数对请求参数进行检测,检测通过再发送请求。
响应拦截器作用:在服务器返回结果页面处理之前,响应拦截器进行一些预处理。

/设置请求拦截器/
axios.interceptors.request.use(function(config){
  return config;
}, function(error){
  return Promise.reject(error);
})
/设置响应拦截器/
axios.interceptors.response.use(function(config){
  return config;
}, function(error){
  return Promise.reject(error);
})

axios取消请求

下面使用一个案例

<body>
  <div class="container">
      <button>发送请求</button>
      <button>取消请求</button>
  </div>
  <script>
    const btns = document.querySelectorAll('button');
    /2.声明全局变量/
    let cancel = null;
    //发送请求
    btns[0].onclick = function(e){
      /检测上一次的请求是否已经完成, 防止重复点击/
      if(cancel !== null) cancel();
      axios({
        method: 'GET',
        url: 'http://localhost:3000/posts',
        /1.添加配置对象的属性/
        cancelToken: new axios.CancelToken(function(){
          cancel = c;  /3. 将c的值赋给cancel/
        });
      }).then(response => (response => { 
        console.log(response);
        cancel = null;
      })
    };
    /取消请求123步/
  </script>
</body>

axios文件结构说明

axios安装后文件结构如下图,下面就目录结构中重要的文档内容进行解释说明
axios文件结构
dist文件夹】项目输出目录。
lib文件夹】项目源码目录。
lib/adapters文件夹】定义请求的适配器xhr、http
lib/adapters/http.js】实现http适配器(包装http包),node.js端发送HTTP请求。
lib/adapters/xhr.js】实现xhr适配器(包装xhr对象),前端发送axios请求的文件。
lib/cancel文件夹】定义取消功能。
lib/cancel/Cancel.js】构造函数,用来创建取消时的错误对象。
lib/cancel/CancelToken.js】取消请求的构造函数 new axios.CancelToken
lib/cancel/isCancel.js】检验参数是否为取消对象
lib/core文件夹】一些核心功能
lib/core/Axios.jsaxios的核心主类
lib/core/buildFullPath.js】构建完整URL的函数文件
lib/core/createError.js】创建指定信息的Error对象
lib/core/dispatchRequest.js】用来调用http请求适配器方法发送请求的函数
lib/core/enhanceError.js】更新错误对象的函数文件
lib/core/interceptorManager.js】拦截管理器构造函数
lib/core/mergeConfig.js】合并配置
lib/core/settle.js】暴露函数 根据响应状态码改变promise的状态
lib/core/transformData.js
lib/helpers文件夹】功能函数
lib/helpers/bind.js】返回一个新的函数,并将新函数this绑定到一个对象上
lib/helpers/bindURL.js】创建一个URL将参数缀到URL后,返回格式化后的内容
lib/helpers/cookies.js】暴露cookie处理的函数
lib/helpers/deprecatedMethod.js】控制台提示不赞成使用的方法(使用较少)
lib/helpers/isAbsoluteURL.js】判断URL是否为绝对路径
lib/helpers/isURLSameOrigin.js】判断是否为同源的URL
lib/axios.jsaxios入口文件
lib/defaults.jsaxios配置文件
lib/utils.js】工具函数文件

axios的创建过程

其中【lib/axios.jsaxios入口文件的文件内容如下

//引入工具
var utils = require('./utils');
//引入绑定函数 创建函数
var bind = require('./helpers/bind');  //创建函数的
//引入axios主文件
var Axios = require('./core/Axios');
//引入合并配置的函数
var mergeConfig = require('./core/mergeConfig');
//导入默认配置
var default = require('./default');

......

axios对象创建过程模拟实现
axios发送请求过程详解
模拟实现axios发送请求
axios拦截器工作原理
模拟实现axios拦截器功能
axios取消请求工作原理
模拟实现axios取消请求功能
axios源码分析总结

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值