axios 介绍与源码分析
axios 是一个基于 promise 的 异步请求API ,便捷的 ajax 请求 ,可在服务器端 发送 http,也可以在浏览器端 发生ajax
要学习之前就必须先搭建一个 服务端
快速的服务器搭建框架 express 或者是 json-server
这里我们使用 json-server 来搭建后端服务器
安装包 npm -g json-server
json-server --watch json文件
json-server 快速搭建一个 基于json 数据的服务
json-server 安装部署
Install JSON Server
npm install -g json-server
Create a db.json file with some data
{
"posts": [
{ "id": 1, "title": "json-server", "author": "typicode" }
],
"comments": [
{ "id": 1, "body": "some comment", "postId": 1 }
],
"profile": { "name": "typicode" }
}
Start JSON Server
json-server --watch db.json
Now if you go to http://localhost:3000/posts/1, you'll get
{ "id": 1, "title": "json-server", "author": "typicode" }
axios 的使用
npm install axios 安装包管理安装或者 搜索 cdnboot 外部地址安装
axios 的配置属性
配置键值对的属性
url 指明 要给谁发送请求(这里写完整路径也可以),method :‘get/post’ baseURL: ‘主要的url地址’
transformRequest:[function(data,headers){}]
带反抖功能的 axios请求
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/1.1.3/axios.js"></script>
</head>
<body>
<button>发送GET请求</button>
<button>取消请求</button>
<script>
const btns= document.querySelectorAll('button');
let cancel=null;
btns[0].onclick=function(){
if(cancel!==null){
cancel();
}
axios({
method:'GET',
url:'http://localhost:3000/posts',
cancelToken: new axios.CancelToken(function(c){
cancel=c;
})
}).then(response=>{
console.log(response);
cancel =null;
})
};
btns[1].onclick=function(){
cancel();
}
</script>
</body>
</html>