Axios拦截器
拦截器的作用:
在请求或响应被 then 或 catch 处理前拦截它们
说白了就是,在请求的时候,将请求拦截下来,可以给请求添加数据,或者查看该次请求;响应也是一样,将响应拦截下来,可以给响应的数据再添加数据,或者查看该次响应。
使用语法:
请求拦截器:
axios.interceptors.request.use(callback);
响应拦截器:
axios.interceptors.response.use(callback);
callback是一个回调函数,回调函数的默认值就是该次的请求或者响应
interceptors的英文意思是:截击机;拦截 的意思
请求的网址是 http://jsonplaceholder.typicode.com/
这个网站提供了免费的假API
请求拦截器Demo:
axios.interceptors.request.use((config)=>{
onsole.log("请求拦截器=>",config);
return config;
})
document.body.onload=()=>{
axios.get("http://jsonplaceholder.typicode.com/todos").then((date)=>{
console.log(date);
}).catch((err)=>{
console.log(err);
});
}
我们可以将请求拦截下来,再添加数据
axios.interceptors.request.use((config)=>{
console.log("请求拦截器=>",config);
config.data={
cesi1:{
name:"测试1",
content:"内容1"
},
cesi2:{
name:"测试2",
content:"内容2"
},
}
return config
});
document.body.onload=()=>{
axios.get("http://jsonplaceholder.typicode.com/todos").then((date)=>{
console.log(date);
}).catch((err)=>{
console.log(err);
});
}
在拦截器添加数据的目的是为了方便——当多个请求需要携带同一个数据去发送时,可以直接在拦截器处添加数据,这样子就不用在每个请求内添加数据。
响应拦截器Demo:
axios.interceptors.response.use((config)=>{
console.log("拦截器=>",config);
return config;
})
document.body.onload=()=>{
axios.get("http://jsonplaceholder.typicode.com/todos").then((date)=>{
console.log(date);
}).catch((err)=>{
console.log(err);
});
}
我们可以给响应拦截器添加数据:
axios.interceptors.response.use((config)=>{
console.log("拦截器=>",config);
config.data.obj="hello";
return config;
})
document.body.onload=()=>{
axios.get("http://jsonplaceholder.typicode.com/todos").then((date)=>{
console.log(date);
}).catch((err)=>{
console.log(err);
});
}
不管是 请求拦截器 还是 响应拦截器,在拦截器中的 return 非常重要; 有return的拦截可以继续下一步,例如 请求拦截器,没有return ,则请求拦截后就不发送了;响应拦截器没有return,则响应数据给拦截后,并没有继续响应。
拦截器的顺序是在请求或者响应前的,请求是先经过拦截器再发送请求,响应是先经过拦截器再继续响应。
Demo:
axios.interceptors.response.use((config)=>{
console.log("拦截器=>",config);
config.data.obj="hello";
// return config;//这里把 returm 注销了
})
document.body.onload=()=>{
axios.get("http://jsonplaceholder.typicode.com/todos").then((date)=>{
console.log(date);
}).catch((err)=>{
console.log(err);
});
}