拦截器

可以全局进行拦截器设置。拦截器在发送请求前或响应返回时做一些特殊的处理。

拦截器的注册

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
})
})

最新文章

  1. Oracle数据库操作知道
  2. 【学】React的学习之旅1
  3. RHCA-红帽认证架构师
  4. 【caffe】未定义函数或变量caffe_
  5. CSS3初学篇章_3(属性选择符/字体样式/元素样式)
  6. AngularJs记录学习03
  7. [转载]jquery获取元素索引值index()方法:
  8. libtiff库使用
  9. Spring自学教程-ssh整合(六)
  10. Java集合源码分析之 LinkedList
  11. BZOJ4695 最假女选手(势能线段树)
  12. UE4入门(二)建立和打开项目
  13. 关于IDEA每次修改HTML,Css等静态资源文件都需要重启的设置修改
  14. (CCPC-Final 2018)K - Mr. Panda and Kakin
  15. SqlServer 凭据
  16. MongoDB复制集的工作原理介绍(二)
  17. cookie和session的区别,session的生命周期,
  18. Linux下安装 mongodb
  19. C#实现相似QQ的隐藏浮动窗口、消息闪动
  20. 使用Redis进行简单的数据缓存

热门文章

  1. mysql10---索引优化
  2. c# 字节高低位
  3. JavaScript 实现的 SHA1 散列
  4. 并不对劲的bzoj1861: [Zjoi2006]Book 书架
  5. BZOJ3732:Network(LCT与最小生成树)
  6. Violet蒲公英
  7. appium学习【四】:第一个appium脚本
  8. Python Import机制备忘-模块搜索路径(sys.path)、嵌套Import、package Import
  9. E20180219-hm-xa
  10. 最小割树Gomory–Hu tree