axios的介绍和特点
3.1 axios是什么?
- 前端最流行的ajax请求库
- react/vue官方都推荐使用axios发ajax请求
- 文档:https://github.com/axios.axios
3.2 axios特点
- 基于promise的异步ajax请求库
- 浏览器端/node端都可以使用
- 支持请求/响应拦截器
- 支持请求取消
- 请求/响应数据转换
- 批量发送多个请求
3.3 axios常用语法
axios(config):通用/最本质的发任意类型请求的fs
aios(url[, config]):可以指定url发get请求
axios.request(config):等同于axios(config)
axios.get(url[, config]):发get请求
axios.delete(url[, config]):发delete请求
axios.post(url[, data, config]):发post请求
axios.put(url[, data, config]):发put请求
axios.defaults.xxx:请求的默认全局配置
axios.interceptors.request.use():添加请求拦截器
axios.interceptors.response.use():添加响应拦截器
axios.create([config]):创建一个新的axios(它没有下面的功能)
axios.Cancle():用于创建取消请求的错误对象
axios.CancleToken():用于创建取消请求的token对象
axios.isCancle():是否是一个取消请求的错误
axios.all(promise):用于批量执行多个异步请求
axios.spread():用来指定接收所有成功数据的回调函数的方法
//指定默认位置
axios.defaults.baseURL = 'http://localhost:3000'
//1.GET请求:从服务器端获取数据
function testGet(){
axios({
url: '/posts',
params: {
id: 1
}
})
}.then(response => {
console.log('/posts get', response.data)
})
//2.POST请求:向服务器端添加新数据
function testPost(){
axios({
url: '/posts',
method: 'POST',
data: {"title": "json-server4", "author": "typicode"}
}).then(response => {
console.log('/posts post', response.data)
})
}
//3.PUT请求:更新服务器端已有数据
function testPut(){
axios({
url:'/posts/4',
method: 'put',
data:{"title": "json-server5", "author": "typicode"}
}).then(response => {
console.log('/posts put', response.data)
})
}
//4.DELETE请求:更新服务器端已有数据
function testPut(){
axios({
url:'/posts/5',
method: 'delete',
}).then(response => {
console.log('/posts put', response.data)
})
}
3.4 难点语法的理解和使用
3.4.1 axios.create(config)
-
根据指定配置创建一个新的axios,也就是每个新的axios都有自己的配置
-
新axios只是没有取消请求和批量发请求的方法,其他所有语法都是一致的
-
为什么要设计这个语法?
(1) 需求:项目中有部分接口需要的配置和另一部分接口需要的配置不太一样,如何处理
(2) 解决:创建2个新axios,每个都有自己特有的配置,分别应用到不同要求的接口请求中
axios.defaults.baseURL = 'http://localhost:3000'
//使用axios发请求
axios({
url: '/posts' //请求3000
})
const instance = axios.create({
baseURL = 'http://localhost:4000'
})
//使用instance(函数/对象)发请求
/*
instance({
url: '/xxx' //请求4000
})
*/
instance.get('/xxx')
3.4.2 拦截器及其运行流程
//添加请求拦截器(回调函数)
axios.interceptors.request.use(
//成功的回调和失败的回调
config => {
console.log('request interceptor1 onResolved()')
return config
},
error => {
console.log('request interceptor1 onRejected()')
return Promise.reject(error)
}
)
//添加响应拦截器
axios.interceptors.response.use(
response => {
console.log('response interceptor1 onResolved()')
return response
},
function(error) {
console.log('reuqest interceptor1 onRejected()')
return Promise.reject(error)
}
)
axios.get('http://localhost:/posts')
.then(response => {
console.log('data', response.data)
})
.catch(response => {
console.log('error', error,message)
})
3.4.3 取消请求
-
基本流程
配置cancelToken对象
缓存用于俏销请求的cancel函数
在后面特定实际调用cancel函数取消请求
在错误回调中判断如果error是cancel,做相应处理
-
实现功能
//添加请求拦截器 axios.interceptors.request.use((config) => { //在准备发请求之前,取消未完成的请求 if(typeof cancel === 'function'){ cancel('取消请求') } //添加一个cancelToken的配置 config.cancelToken = new axios.CancelToken(function executer(c) { //c是用于取消当前请求的函数 //保存取消函数,用于之后可能需要取消当前请求 cacle = c; }) return config }) //添加响应拦截器 axios.interceptors.response.use( response => { cancel = null return response }, error => { if(axios.isCancel(error)){ //取消请求的错误 //cancel = null console.log('请求取消的错误', error.message) //做相应处理 //中断promise连接 return new peomise(() => {}) }else { //请求出错了 cancel = null //将错误往下传递 //throw error return Promise.reject(error) } } ) let cancle //用于保存取消请求的函数 function getProduct1() { axios({ url: 'http://localhost:4000/product1', }).then( response => { console.log('请求1成功了', response.data) }, //异步执行 error => { //只处理请求失败的情况,取消请求的错误的不用 console.log('请求1失败了', error.message) } ) } function getPromise2() { axios({ url: 'http://localhost:4000/product2', }).then( response => { console.log('请求2成功了', response.data) }, error => { console.log('请求2失败了', error.message) } ) } function cancleReq() { //执行取消请求的函数 if(typeof cancel === 'function'){ cacle('强制取消请求') }else { console.log('没有可取消的请求') } }