axios 简介
axios 是一个基于Promise 用于浏览器和 nodejs 的 HTTP 客户端,它本身具有以下特征:
- 从浏览器中创建 XMLHttpRequest
- 从 node.js 发出 http 请求
- 支持 Promise API
- 拦截请求和响应
- 转换请求和响应数据
- 取消请求
- 自动转换JSON数据
- 客户端支持防止 CSRF/XSRF
1.axios通常在vue中作为ajax请求数据
请求后端数据可分为get请求和post请求,首先引入axios.js
1.1.axios 执行get请求
通用语法模板
axios.get("url",{params:{key:value}}
.then((res)=>{
console.log(res.data);
})
.catch(function(error){});
第一个参数是url地址,第二个是向url传的参数
.then中的参数是个回调函数,函数中的this指向window,为了让this指向vue便于以后的操作,使用箭头函数
.catch是请求失败调用的方法,可以省略
实例:请求getData.php,传入参数title:眼镜
axios.get("getData.php",{params:{title:"眼镜"}})
.then(function(res){
console.log(res.data)
})
1.2.axios执行post请求
通用语法模板
axios.post("url",{key:value})
.then((res)=>{
console.log(res.data);
})
.catch(function(error){});
post和get大致相同,只是第二个参数不需要params,可以直接传参
2.axios 拦截器
在请求或响应被 then 或 catch 处理前拦截它们。通俗点说就是发起请求后但是数据还未到达时,或者接收数据后 做的相应的操作
函数中的参数是配置项,并返回
2.1 发起请求前
发起请求后数据未到达时对应的操作
比如让原先有style:display="none"的loading 显示
axios.interceptors.request.use(function(config){
loading.style.display="block";
return config;
})
2.2 发起请求后
发起请求后得到数据,让loading消失
axios.interceptors.response.use(function(res){
//隐藏loading
loading.style.display="none";
return res;
})
2.3 完整拦截器例子
点击获取数据按钮,数据过来之前出现landing
接收数据后landing消失,data中得到数据
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<button id="getdata">获取数据</button>
<span id="l" style="display: none;">landing</span>
<div id="data"></div>
<script type="text/javascript" src="axios.js" ></script>
<script>
getdata.onclick=function(){
axios.interceptors.request.use(function(config){
l.style.display="block"
return config;
})
axios.interceptors.response.use(function(res){
l.style.display='none';
return res;
})
axios.get("getData.php",{params:{title:"眼镜"}})
.then(function(res){
console.log(res.data)
data.innerHTML=res.data
})
}
</script>
</body>
</html>