axios就是一个基于Promise的,发送http请求的一个工具库
特点
1、支持Promise API
2、拦截请求和响应。拦截请求,可以过滤请求参数;拦截响应,可以处理响应异常
3、取消请求。请求可以手动取消
要想使用axios必须得先安装axios
安装
使用npm安装
$ npm install axios
使用cdn
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
再main.js中导入
import axios from 'axios'
new Vue({
el: '#app',
router,
axios // 加入axios
})
调用接口
get请求:
// 第一种方式 将参数直接写在url中
axios.get('url?id=123')
.then((res) => {
console.log(res)
})
.catch((err) => {
console.log(err)
})
// 第二种方式 将参数直接写在params中
axios.get('url', {
params: {
id: 123
}
})
.then((res) => {
console.log(res)
})
.catch((err) => {
console.log(err)
})
post请求
使用post请求时注意执行post请求的入参,不能写在params字段中,跟get请求方法有所区别
axios.post('url', {
id: 123
})
.then((res) => {
console.log(res)
})
.catch((err) => {
console.log(err)
})
url路径
method传值方式post、get
params:即将于请求一起发送的url参数(一般只用于get请求)一般是对象类型
data:作为请求主体被发送是数据(一般只用于post请求)一般是对象类型
.then 里是后台返回结果
.catch里是网络错误或后台服务器出bug等
timeout:超时时间,超过时间,请求将被中断
withCredentials:表示跨域请求时是否需要使用凭证
responseType:响应数据的类型,默认是’json’,可以是’text’, ‘json’,‘document’,‘arraybuffer’,‘blob’,‘stream’
执行多个并发
当有一个请求出错时,就会报错
function getfan() {
return axios.get('/getfan?id=123')
}
function getGao() {
return axios.get('getGao?id=123')
}
axios.all([getfan(), getGao()])
.then(
axios.spread(function(acct, perms) { // 处理并发请求的助手函数
console.log(acct, perms) // 全部请求成功
})
).catch(err => {
console.log(err) // 只要任意一个请求出错
})
拦截器
拦截器相当于是个过滤器:就是把不想要的或不想显示的内容给过滤掉。减轻代码冗余,提高重用率。
作用:可以构成拦截器栈,完成特定功能。比如日志记录、登录判断、权限检查等作用。
请求前拦截
// 添加请求拦截器
axios.interceptors.request.use(function (con) {
// 在发送请求之前做些什么
return con;
}, function (error) {
// 对请求错误做些什么
return Promise.reject(error);
})
在被then,catch处理前拦截
// 添加响应拦截器
axios.interceptors.response.use(function (response) {
// 对响应数据做点什么
return response;
}, function (error) {
// 对响应错误做点什么
return Promise.reject(error);
});