赞
踩
参考:https://blog.csdn.net/qq_39765048/article/details/117688019
原文更精辟,请支持原文。
axios框架全称(ajax – I/O – system)
是用来实现“异步网络请求
”的。
旧浏览器页面在向服务器请求数据时,因为返回的是整个页面的数据,页面都会强制刷新一下,这对于用户来讲并不是很友好。并且我们只是需要修改页面的部分数据,但是从服务器端发送的却是整个页面的数据,十分消耗网络资源。而我们只是需要修改页面的部分数据,也希望不刷新页面,因此异步网络请求
就应运而生了。但是这里我们最开始使用的是Ajax。
Ajax(Asynchronous JavaScript and XML): 异步网络请求。Ajax能够让页面无刷新的请求数据。
实现ajax的方式有多种,如jQuery封装的ajax,原生的XMLHttpRequest,以及axios。
利弊:
Axios(ajax i/o system): 本质上还是对原生XMLHttpRequest的封装,可用于浏览器和nodejs的HTTP客户端,只不过它是基于Promise的,符合最新的ES规范。
特点:
(1)安装
npm install axios
(2)引用
main.js
import axios from 'axios'
Vue.prototype.$axios = axios
(3)使用axios
<script>
export default {
mounted(){
this.$axios.get('/xxxx').then(res=>{
console.log(res.data);
})
}
}
</script>
一般不会上面使用,大多会进行模块封装(详见其他Axios封装文章)
get post put patch delete
this.$axios.all([
this.$axios.get('/goods.json'),
this.$axios.get('/classify.json')
]).then(
this.$axios.spread((goodsRes,classifyRes)=>{
console.log(goodsRes.data);
console.log(classifyRes.data);
})
)
(1)创建axios实例
let instance = this.$axios.create({
baseURL: 'http://localhost:9090',
timeout: 2000
})
instance.get('/xxxx').then(res=>{
console.log(res.data);
})
配置说明:
(2)axios全局配置
//配置全局的超时时长
this.$axios.defaults.timeout = 2000;
//配置全局的基本URL
this.$axios.defaults.baseURL = 'http://localhost:8080';
(3)axios实例配置
let instance = this.$axios.create();
instance.defaults.timeout = 3000;
(4)axios请求配置
this.$axios.get('/goods.json',{
timeout: 3000
}).then()
优先级为:请求配置 > 实例配置 > 全局配置
(1)请求拦截器
this.$axios.interceptors.request.use(config=>{
// 发生请求前的处理
return config
},err=>{
// 请求错误处理
return Promise.reject(err);
})
//或者用axios实例创建拦截器
let instance = $axios.create();
instance.interceptors.request.use(config=>{
return config
})
(2)响应拦截器
this.$axios.interceptors.response.use(res=>{
//请求成功对响应数据做处理
return res //该返回对象会传到请求方法的响应对象中
},err=>{
// 响应错误处理
return Promise.reject(err);
})
(3)取消拦截
let instance = this.$axios.interceptors.request.use(config=>{
config.headers = {
token: ''
}
return config
})
//取消拦截
this.$axios.interceptors.request.eject(instance);
this.$axios.get('/url').then(res={
}).catch(err=>{
//请求拦截器和响应拦截器抛出错误时,返回的err对象会传给当前函数的err对象
console.log(err);
})
let source = this.$axios.CancelToken.source();
this.$axios.get('/goods.json',{
cancelToken: source
}).then(res=>{
console.log(res)
}).catch(err=>{
//取消请求后会执行该方法
console.log(err)
})
//取消请求,参数可选,该参数信息会发送到请求的catch中
source.cancel('取消后的信息');
结束。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。