Vue 拦截器的使用
2024-09-04 14:55:16
拦截器
可以全局进行拦截器设置。拦截器在发送请求前或响应返回时做一些特殊的处理。
拦截器的注册
Vue.http.interceptors.push({
request: function ( request ) {
// 更改请求类型为POST
request.method = 'POST';
return request;
},
response: function ( response ) {
// 修改返回数据
response.data = [{
custom: 'custom'
}];
return response;
}
});
工厂函数注册
Vue.http.interceptors.push(function () {
return {
request: function ( request ) {
return request;
},
response: function ( response ) {
return response;
}
}
});
Vue.http.interceptors.push(function ( request, next ) {
// 请求发送前的处理逻辑
next(function () {
// 请求发送后的处理逻辑
// 更具请求的状态, response参数会返回给 successCallback或errorCallback
return response
});
});
实现的功能:
AJAX请求的loading界面
Vue.http.interceptors.push((request, next) => {
// 通过控制 组件的`v-show`值显示loading组件
loading.show = true;
next((response) => {
loading.show = false
return response
});
});
请求失败时的提示对话框
vue-resource 拦截器使用
在vue项目使用vue-resource的过程中,临时增加了一个需求,需要在任何一个页面任何一次http请求,增加对token过期的判断,如果token已过期,需要跳转至登录页面。如果要在每个页面中的http请求操作中添加一次判断,那么会是一个非常大的修改工作量。
vue-resource的interceptors拦截器的作用正是解决此需求的妙方。在每次http的请求响应之后,如果设置了拦截器如下,会优先执行拦截器函数,获取响应体,然后才会决定是否把response返回给then进行接收。那么我们可以在这个拦截器里边添加对响应状态码的判断,来决定是跳转到登录页面还是留在当前页面继续获取数据。
main.js里面设置:
Vue.http.interceptors.push((request, next) => {
console.log(this)//此处this为请求所在页面的Vue实例
// modify request
request.method = 'POST';//在请求之前可以进行一些预处理和配置 // continue to next interceptor
next((response) => {//在响应之后传给then之前对response进行修改和逻辑判断。对于token时候已过期的判断,就添加在此处,页面中任何一次http请求都会先调用此处方法 response.body = '...';
return response; });
});
Vue.http.interceptors.push((request, next) =>{
//登录成功后将后台返回的toekn在本地存下来,每次请求从sessionStorage中拿到存储的token值
let token=sessionStorage.getItem('STORAGE_TOKEN');
if(toekn){
//如果请求时toekn存在,就为每次请求的headers中设置好toekn,后台根据headers中的toekn判断是否放行
request.headers.set('toekn',toekn);
}
next((response) => {
return response;
});
});
拦截器
Vue.http.interceptors.push((request, next) => {
//console.log(Login.item);
var tokens = localStorage.getItem('token');
request.headers.set('Authorization', tokens);
//console.log(request.headers);
help.showLoading = true;
next((response) => {
//console.log(response);
help.showLoading = false;
return response
})
})
最新文章
- Oracle数据库操作知道
- 【学】React的学习之旅1
- RHCA-红帽认证架构师
- 【caffe】未定义函数或变量caffe_
- CSS3初学篇章_3(属性选择符/字体样式/元素样式)
- AngularJs记录学习03
- [转载]jquery获取元素索引值index()方法:
- libtiff库使用
- Spring自学教程-ssh整合(六)
- Java集合源码分析之 LinkedList
- BZOJ4695 最假女选手(势能线段树)
- UE4入门(二)建立和打开项目
- 关于IDEA每次修改HTML,Css等静态资源文件都需要重启的设置修改
- (CCPC-Final 2018)K - Mr. Panda and Kakin
- SqlServer 凭据
- MongoDB复制集的工作原理介绍(二)
- cookie和session的区别,session的生命周期,
- Linux下安装 mongodb
- C#实现相似QQ的隐藏浮动窗口、消息闪动
- 使用Redis进行简单的数据缓存