Axios基础使用
//添加一篇新的文章btns[1].onclick = function(){//发送AJAX请求axios({//请求类型method:'POST',//URLurl:'http://localhost:3000/posts',//设置请求体data:{title:'今天天气不错',author:'张三'}}).then(response => {console.log(response);});}
Axios其他使用
//发送 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);})}
Axios默认配置
//默认配置axios.defaults.method = 'GET';//设置默认的请求类型为GETaxios.defaults.baseURL = 'http://localhost:3000';//设置基础URLaxios.defaults.params = {id:100};axios.defaults.timeout = 3000;btns[0].onclick = function(){axios({url:'/posts'}).then(response => {console.log(response);})}
Axios实际是调了Axios.prototype.request函数
Axios取消请求
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 的值赋值给 cancelcancel = c;})}).then(response=>{console.log(response);//将cancel的值初始化cancel = null;})}//绑定第二个事件 取消请求btns[1].onclick = function(){cancel();}
Axios取消请求的原理
Axios取消请求最核心的方法是CanelToken。
CancelToken内部维护了一个Promise对象,其默认状态是pending。axios把取消请求的代码放在promise成功的回调中,只要改变promise执行的状态,就可以取消请求。而这个将promise状态改变的函数暴露给了外层,在需要的时候去执行它,promise的状态就改变了。
