【Axios的概述和基本使用】
Axios 是什么?
- 前端最流行的
Ajax
请求库
- react/vue 官方都推荐使用 axios 发ajax 请求
- 文档: https://github.com/axios/axios
Axios 特点
- 基于 xhr + promise 的异步 ajax请求库
- 浏览器端/node 端都可以使用
- 支持请求/响应拦截器
- 支持请求取消
- 请求/响应数据转换
- 批量发送多个请求
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: 请求的默认全局配置(method\baseURL\params\timeout…)
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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| { url: '/user',
method: 'get',
baseURL: 'https://some-domain.com/api/',
headers: {'X-Requested-With': 'XMLHttpRequest'},
params: { ID: 12345, name:"Jack" },
data: { firstName: 'Fred' },
data: 'Country=Brasil&City=Belo Horizonte',
timeout: 1000,
responseType: 'json',
responseEncoding: 'utf8',
maxContentLength: 2000,
maxBodyLength: 2000,
validateStatus: function (status) { return status >= 200 && status < 300; }
|
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
| <button id="btn1">发送get请求</button> <br><br> <button id="btn2">发送post请求</button><br><br> <button id="btn3">发送put请求</button><br><br> <button id="btn4">发送delete请求</button>
<hr>
<div>其他发送请求的api:</div><br><br> <button id="btn5">发送get请求1</button> <br><br> <button id="btn6">发送post请求1</button><br><br> <button id="btn7">发送put请求1</button><br><br> <button id="btn8">发送delete请求1</button> <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> <script> document.getElementById("btn1").onclick = function(){ axios({ method:"GET", url:"http://localhost:3000/posts/1" }).then(response=>{ console.log(response); }) };
document.getElementById("btn2").onclick = function(){ axios({ method:"POST", url:"http://localhost:3000/posts", data:{ title:"axios学习", author:"Yehaocong" } }).then(response=>{ console.log(response); }) }; document.getElementById("btn3").onclick = function(){ axios({ method:"PUT", url:"http://localhost:3000/posts/2", data:{ title:"axios学习", author:"Liaoxiaoyan" } }).then(response=>{ console.log(response); }) }; document.getElementById("btn4").onclick = function(){ axios({ method:"DELETE", url:"http://localhost:3000/posts/2", }).then(response=>{ console.log(response); }) };
document.getElementById("btn5").onclick = function(){ axios.get("http://localhost:3000/posts/1") .then(response=>{ console.log(response); }) };
document.getElementById("btn6").onclick = function(){ axios.post("http://localhost:3000/posts", {title:"axios学习2", author:"Yehaocong2"}) .then(response=>{ console.log(response); }) }; document.getElementById("btn7").onclick = function(){ axios.put("http://localhost:3000/posts/2",{title:"axios学习", author:"Liaoxiaoyan"}) .then(response=>{ console.log(response); }) }; document.getElementById("btn8").onclick = function(){ axios.delete("http://localhost:3000/posts/3") .then(response=>{ console.log(response); }) };
|

默认配置
可以设置全局默认配置,是为了避免多种重复配置在不同请求中重复,比如baseURL、timeout等,这里设置baseURL。
1 2 3 4 5 6 7
| axios.defaults.baseURL="http://localhost:3000";
axios.get("/posts/1") .then(response=>{ console.log(response); })
|
创建一个新的axios对象
根据指定配置创建一个新的 axios, 也就是每个新 axios 都有自己的配置
新 axios 只是没有取消请求和批量发请求的方法, 其它所有语法都是一致的
为什么要设计这个语法?
(1) 需求: 项目中有部分接口需要的配置与另一部分接口需要的配置不太一样, 如何处理(比如有多个baseURL需要指定)
(2) 解决: 创建2 个新axios, 每个都有自己特有的配置, 分别应用到不同要求的接口请求中
1 2 3 4 5 6 7 8 9 10
| const instance = axios.create({ baseURL: 'http://localhost:3000' })
instance({ url: '/posts' })
instance.get('/posts')
|
拦截器
请求拦截器(在发送请求前,使用函数对请求的参数和内容进行处理和检测,若请求有问题可直接进行拦截->取消,后进先执行=则后面的请求拦截器先执行)
响应拦截器(对响应的结果预处理,先进先执行=前面的响应拦截器先执行)
1)请求拦截器:
① 在真正发送请求前执行的回调函数
② 可以对请求进行检查或配置进行特定处理
③ 失败的回调函数,传递的默认是error
④ 成功的回调函数,传递的默认是config(也必须是)
2)响应拦截器
① 在请求得到响应后执行的回调函数
② 可以对响应数据进行特定处理
③ 成功的回调函数,传递的默认是response
④ 失败的回调函数,传递的默认是error
3)请求转换器:对请求头和请求体数据进行特定处理的函数
响应转换器:将响应体json字符串解析为js对象或数组的函数
- 说明: 调用axios()并不是立即发送ajax 请求, 而是需要经历一个较长的流程
- 流程: 请求拦截器2 => 请求拦截器1 => 发ajax 请求 => 响应拦截器1 => 响应拦截器2 => 请求的回调
- 注意: 此流程是通过 promise 串连起来的, 请求拦截器传递的是config, 响应拦截器传递的是response
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
| script> axios.interceptors.request.use( function (config) { console.log("请求拦截器 成功 1号"); config.params = { a: 100 }; return config; }, error => { console.log("请求拦截器 失败 1号"); return Promise.reject(error); } );
axios.interceptors.request.use( function (config) { config.timeout = 5000; console.log("请求拦截器 成功 2号"); config.timeout = 2000; return config; }, error => { console.log("请求拦截器 失败 2号"); return Promise.reject(error); } );
axios.interceptors.response.use( function (response) { console.log("响应拦截器 成功 1号"); return response.data; }, function (error) { console.log("响应拦截器 失败 1号"); return Promise.reject(error); } );
axios.interceptors.response.use( function (response) { console.log("响应拦截器 成功 2号"); return response; }, function (error) { console.log("响应拦截器 失败 2号"); return Promise.reject(error); } );
axios({ method: "GET", url: "http://localhost:3000/posts", }) .then((response) => { console.log("自定义回调处理成功的结果"); }) .catch((reason) => { console.log(reason); }); </script>
|

取消请求
0.22版本之前可以使用,0.22开始被废弃
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| <body> <div class="container"> <h1 class="page-header">axios取消请求</h1> <button class="btn btn-primary">发送请求</button> <button class="btn btn-warning">取消请求</button> </div> </body> <script> const btns = document.querySelectorAll("button"); let cancel = null; btns[0].onclick = () => { if (cancel !== null) { cancel(); } axios({ method: "GET", url: "http://localhost:3000/posts", cancelToken: new axios.CancelToken((c) => { cancel = c; }), }).then((response) => { console.log(response); cancel = null; }); };
btns[1].onclick = () => { cancel(); }; </script>
|
0.22新方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.27.2/axios.min.js"></script> let btn = document.querySelectorAll('button'); const controller = new AbortController(); btn[0].onclick = function () { axios( { url:'https://api.uomg.com/api/get.kg?songurl=https://node.kg.qq.com/play?s=YaCv8EYfJunVWYcH', signal: controller.signal }).then(function(response) { console.log(response); }); }
btn[1].onclick = function () { controller.abort() }
|
在vue中封装axios
requests.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| import axios from 'axios';
import store from '@/store';
let requests = axios.create({ baseURL: '/api', timeout: 5000, });
requests.interceptors.request.use(config => { if (store.state.detail.nanoid_token) config.headers.userTempId = store.state.detail.nanoid_token; if (store.state.user.token) config.headers.token = store.state.user.token;
return config; });
requests.interceptors.response.use( res => { return res.data; }, err => { alert(err.message); return new Promise(); } );
export default requests;
|
使用
1 2 3 4
| import requests from '@/api/requests';
export const reqRegister = data => requests({ url: `/user/passport/register`, method: 'post', data });
|
AJAX概述和基本使用
Fetch的概述和基本使用