一、创建实例对象
访问不同的后台链接,使用不同的实例对象发送请求
// 创建实例对象
const requestA = axios.create({
baseURL: '', // 基础访问路径 http://localhost:3000
timeout: 10000, // 设置超时时间
})
// 创建实例对象
const requestB = axios.create({
baseURL: '', // 基础访问路径 http://b.com
timeout: 10000, // 设置超时时间
})
//使用 request与axios对象的功能 几乎一样
requestA.get('/post').then(res=>{
console.log(res)
})
二、设置请求拦截器
对请求前置处理,可以修改发送请求的设置,触发顺序是先进后出,先写的后验证。
requestA.interceptors.request.use(
config=>{
return config
},
error=>{
return Promise.reject(error)
}
)
在config=>{}中可以对配置进行修改, 如:
config.timeout=2000
config.params={a:100} -----> 请求url变为: http://localhost:3000/post?a=100
后台验证的token一般在此时统一添加到请求配置中
三、设置响应拦截器
对后台响应结果的前置处理,可以简化axios().then(res=>{})中res的数据
触发顺序是先进先出,先写的先修改。
requestA.interceptors.response.use(
response=>{
return response
},
error=>{
return Promise.reject(error)
}
)
四、取消请求
多次点击请求按钮,如果上一次的请求还没完成,则取消上一次请求,发送本次请求
// 定义全局变量
let cancel = null
//给按钮添加点击事件
btn.onclick = function(){
//检测上次请求是否完成
if(cancel !== null){
cancel() // 调用cancel函数,取消上一次请求
}
axios.get(
'http://localhost:3000/posts',
{ // 添加配置对象的属性
cancelToken: new axios.CancelToken(function(c){
// 将c的值赋值给cancel
cancel = c
})
}
).then(res => {
console.log(res)
// 请求完成,将cancel初始化
cancel = null
}