Axios:
Axios,是一个基于promise [5] 的网络请求库,作用于node.js和浏览器中,它是 isomorphic 的(即同一套代码可以运行在浏览器和node.js中)。在服务端它使用原生node.js http模块, 而在客户端 (浏览端) 则使用XMLHttpRequest。 [2]
特性
- 从浏览器创建 XMLHttpRequests
- 从 node.js 创建 http 请求
- 支持 Promise API
- 拦截请求和响应
- 转换请求和响应数据
- 取消请求
- 自动转换JSON数据
- 客户端支持防御XSRF
安装
使用 npm: npm install axios
使用
axios是基于Promise的,因此可以使用Promise API
axios的请求方式:
- axios(config)
- axios.request(config)
- axios.get(url [,config])
- axios.post(url [,data [,config]])
- axios.put(url [,data [,config]])
- axios.delete(url [,config])
- axios.patch(url [,data [,config]])
- axios.head(url [,config])
<script>
//发送GET查询请求
axios({
//请求类型
method:'GET',
//URL
url:'http//localhost:8080/xxx'
}).then(response =>{
console.log(response)
},err=>{
console.log(err);
});
//发送添加POST请求
axios({
//请求类型
method:'POST',
//URL
url:'http//localhost:8080/xxx',
//设置请求体
data:{
xx:xx,
xxx:xxx
}
}).then(response =>{
console.log(response)
},err=>{
console.log(err);
});
//发送更新PUT请求
axios({
//请求类型
method:'PUT',
//URL
url:'http//localhost:8080/xxx/xxid',
//设置请求体
data:{
xx:xx,
xxx:xxx
}
}).then(response =>{
console.log(response)
},err=>{
console.log(err);
});
//发送删除DELETE请求
axios({
//请求类型
method:'DELETE',
//URL
url:'http//localhost:8080/xxx/xxid',
}).then(response =>{
console.log(response)
},err=>{
console.log(err);
});
</script>
其他方式发送请求
<script>
//发送GET请求
//axios()一样
axios.request({
method:'GET',
url:'http://localhost:8080/xxxs'
}).then(response =>{
console.log(response)
},err=>{
console.log(err);
})
//发送POST请求
//axios()
axios.post(
//URL
'http://localhost:8080/xxxs',
{
//参数
"xx":xx
"xxx":"xxx"
}).then(response =>{
console.log(response);
},err=>{
console.log(err);
})
</script>
axios默认设置
<script>
// 引入axios
import axios from 'axios';
// 创建axios实例
const httpService = axios.create({
// 请求超时时间
timeout: 3000 // 需自定义
});
</script>
拦截器
响应拦截器 在我们处理结果之前帮助我们对返回的结果进行一个预处理,比如格式化数据
// request拦截器
httpService.interceptors.request.use(
config => {
console.log(config.url);
return config;
},
error => {
// 请求错误处理
Promise.reject(error);
}
)
取消请求
<script>
// 2.声明全局变量
let cancel = null;
xxx = function() {
if(cancel !== null){
//取消上一次请求
cancel();
}
axios({
method:'GET',
url:'http://localhost:8080/xxxs',
//1.添加配置对象的属性
cancelToken: new axios.CancelToken(function(c){
// 3. 将c的值赋值给 cancel
cancel = c;
})
}).then(response => {
console.log(response);
//将 cancel 的值初始化
cancel = null;
})
}
//执行 cancel 函数来触发取消请求
xxx = function (){
cancel();
}
</script>