🌵 作者主页:💖仙女不下凡💖
🌵 前言介绍:以下👇 内容都是我个人对于前端知识的总结,会定期更新欢迎持续关注!
🌵 欢迎点赞 👍 收藏 ⭐留言 📝 如有错误敬请指正!
🔥 视频地址:尚硅谷2021最新版axios入门与源码解析
🔥学习原因:axios
是目前前端最热门的ajax
请求,vue
与react
都用到了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安装后文件结构如下图,下面就目录结构中重要的文档内容进行解释说明
【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.js
】axios
的核心主类
【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.js
】axios
入口文件
【lib
/defaults.js
】axios
配置文件
【lib
/utils.js
】工具函数文件
axios的创建过程
其中【lib
/axios.js
】axios
入口文件的文件内容如下
//引入工具
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源码分析总结