Vue 拦截器的使用

拦截器

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

拦截器的注册

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

 

posted @ 2017-12-11 14:07  蓝色帅-橙子哥  阅读(9256)  评论(0编辑  收藏  举报