一、axios是什么?
Axios是一个基于promise的HTTP库,类似于jQuery的ajax,用于http请求。可以应用于浏览器端和node.js,既可以用于客户端,也可以用于node.js编写的服务端。
前端最流行的ajax请求库
react/vue官方都推荐使用axios 发ajax 请求
二、特点
- 基于xhr + promise的异步ajax请求库
- 浏览器端/node端都可以使用
- 支持请求/响应拦截器
- 支持请求取消
- 自动转换JSON数据
- 请求/响应数据转换
- 批量发送多个请求
三、使用
1.json文件
在项目的public文件夹下新建.json文件,用于模拟数据。在组建中引入axios,并发起请求。
{
"posts": [
{
"id": 1,
"title": "json-server",
"author": "typicode"
},
{
"id": 2,
"title": "尚硅谷大厂学院上线啦",
"author": "小编"
},
{
"title": "今天天气不错, 还挺风和日丽的",
"author": "张三",
"id": 3
}
],
"comments": [
{
"id": 1,
},
{
"body": "喜大普奔",
"postId": 2,
"id": 2
}
],
"profile": {
"name": "typicode"
}
}
2.基本使用
代码如下(示例):
<script>
//获取按钮
const btns = document.querySelectorAll('button');
//第一个
btns[0].onclick = function(){
//发送 AJAX 请求
axios({
//请求类型
method: 'GET',
//URL
url: 'http://localhost:3000/posts/2',
}).then(response => {
console.log(response);
});
}
//添加一篇新的文章
btns[1].onclick = function(){
//发送 AJAX 请求
axios({
//请求类型
method: 'POST',
//URL
url: 'http://localhost:3000/posts',
//设置请求体
data: {
title: "今天天气不错, 还挺风和日丽的",
author: "张三"
}
}).then(response => {
console.log(response);
});
}
//更新数据
btns[2].onclick = function(){
//发送 AJAX 请求
axios({
//请求类型
method: 'PUT',
//URL
url: 'http://localhost:3000/posts/3',
//设置请求体
data: {
title: "今天天气不错, 还挺风和日丽的",
author: "李四"
}
}).then(response => {
console.log(response);
});
}
//删除数据
btns[3].onclick = function(){
//发送 AJAX 请求
axios({
//请求类型
method: 'delete',
//URL
url: 'http://localhost:3000/posts/3',
}).then(response => {
console.log(response);
});
}
</script>
3.其他使用
//获取按钮
const btns = document.querySelectorAll('button');
//发送 GET 请求
btns[0].onclick = function(){
// axios()
axios.request({
method:'GET',
url: 'http://localhost:3000/comments'
}).then(response => {
console.log(response);
})
}
//发送 POST 请求
btns[1].onclick = function(){
// axios()
axios.post(
'http://localhost:3000/comments',
{
"body": " ",
"postId": 2
}).then(response => {
console.log(response);
})
}
4.基本语法
流程:请求拦截器2=>请求拦截器1=>发ajax请求=>响应拦截器1=>响应拦截器2=>请求的回调 (unshift,push)
- 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, configl):发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():用来指定接收所有成功数据的回调函数的方法
5.取消请求
//获取按钮
const btns = document.querySelectorAll('button');
//2.声明全局变量
let cancel = null;
//发送请求
btns[0].onclick = function(){
//检测上一次的请求是否已经完成
if(cancel !== null){
//取消上一次的请求
cancel();
}
axios({
method: 'GET',
url: 'http://localhost:3000/posts',
//1. 添加配置对象的属性
cancelToken: new axios.CancelToken(function(c){
//3. 将 c 的值赋值给 cancel
cancel = c;
})
}).then(response => {
console.log(response);
//将 cancel 的值初始化
cancel = null;
})
}
//绑定第二个事件取消请求
btns[1].onclick = function(){
cancel();
}
6.请求拦截器
- 在真正发送请求前执行的回调函数
- 可以对请求进行检查或配置进行特定处理
- 成功的回调函数,传递的默认是config(也必须是)
- 失败的回调函数,传递的默认是error
// 请求拦截器
axios.interceptors.request.use(config => {
// 在发送请求前做些什么
return config;
}, err=>{
// 在请求错误的时候的逻辑处理
return Promise.reject(err)
});
7.响应拦截器
- 在请求得到响应后执行的回调函数
- 可以对响应数据进行特定处理
- 成功的回调函数,传递的默认是response
- 失败的回调函数,传递的默认是error
// 响应拦截器
axios.interceptors.response.use(res => {
// 在请求成功后的数据处理
return res;
}, err=>{
// 在响应错误的时候的逻辑处理
return Promise.reject(err)
});
8.默认配置
axios.defaults.method = 'GET';//设置默认的请求类型为 GET
axios.defaults.baseURL = 'http://localhost:3000';//设置基础 URL
axios.defaults.params = {id:100};//url参数
axios.defaults.timeout = 3000;//请求的超时时长,单位毫秒,默认。