专门用来发起异步请求的工具。就类似于之前学习到的ajax,但是因为ajax不太符合我们现代化的项目,所以,axios应运而生。
一、 axios VS ajax
- 区别
1> axios 就是直接对 XHR的封装,没有任何其他对于代码
2> ajax 是jquery中的一个方法,如果要使用的话,还需要引入jq的完整功能文件
- 相同
对XHR的封装
二、关于请求
异步请求工具: ajax 、axios 、fetch
ajax: jquery 的一个方法,封装的XHR
axios: promise 集合 XHR 封装的工具
fetch: 是一个原生js提供的请求对象!
三、axios的快速查询
1> get请求
axios.get(地址).then(() => {
}).catch((err) => {
})
例:
axios.get('http://www.lt.com/index.php/index/news/getNews?page=2').then((res)=>{
console.log(res);
}).catch((err) => {
console.log(err);
})
- get请求传参
1> 将参数跟在地址后边 地址?page=1&limit=10...
2> get方法接收第二个参数
axios.get('http://www.web14ban.com/index.php/index/news/getNews',{
params:{
page:2,
limit:10
}
})
例:
axios.get('http://www.lt.com/index.php/index/news/getNews',{
params:{
page:2,
limit:10
}
}).then((res) => {
console.log(res);
}).catch((res) => {
console.log(err);
})
2> post 请求
axios.post(地址,{参数1:值1,...})
例:
axios.post('http://www.lt.com/index.php/index/user/hasUser',{
username:this.console(res)
});
四、 axios的完整用法
axios({
url:'',
method:'',
timeout:'',
data:{}
}).then().catch()
1> baseURL 基础地址
作用:与你的url地址进行连接
例:
2> 两个数据拦截
transformRequest: [function (data, headers) {
// 对发送的 data 进行任意转换处理
return data;
}],
// `transformResponse` 在传递给 then/catch 前,允许修改响应数据
transformResponse: [function (data) {
// 对接收的 data 进行任意转换处理
return data;
}],
五、并发请求
其实就是axios封装的Promise.all() 方法,而形成了 axios.all() 做并发请求
Promise.all()
Axios 返回的请求是 Promise 对象,我们可以使用 Promise.all() 方法来处理并发请求。该方法接受一个 Promise 数组作为参数,并在所有 Promise 都成功解决后返回一个新的 Promise,该 Promise 的解决值是一个包含所有请求结果的数组。
例:
const axios = require('axios');
const request1 = axios.get('https://api.example.com/resource1');
const request2 = axios.get('https://api.example.com/resource2');
Promise.all([request1, request2])
.then((responses) => {
const response1 = responses[0];
const response2 = responses[1];
// 在这里处理 response1 和 response2
})
.catch((error) => {
// 处理错误
});
六、axios实例
实例可以集成父级所有属性和方法!、
例1:
let instance = axios.create({
method:'post'
})
instance({
url:'xxx',
// method不写默认集成父级的method
})
例2:
let instance = axios.create({
baseURL: 'http://www.web14ban.com/index.php',
timeout: '5000'
})
instance({
url:'/index/news/getNews'
})
instance.get()
instance.post()
七、 拦截器(请求拦截器、响应拦截器)
1> 请求拦截器
axios.interceptors.request.use(function (config) {
// 在发送请求之前做些什么
return config;
}, function (error) {
// 对请求错误做些什么
return Promise.reject(error);
});
- 帮助我们完成的事
1> 添加加载效果
2> 帮助我们完成token验证