vue-resource 全局拦截器

项目中可能会添加超时登录的功能,因此根据tokenid 判断是否超时。如果token已过期,需要跳转至登录页面。

因此需要用到全局拦截器拦截返回的状态

//下边代码添加在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(function(request, next) {
    // ...
    // 请求发送前的处理逻辑
    // ...
    next(function(response) {
        // ...
        // 请求发送后的处理逻辑
        // ...
        // 根据请求的状态,response参数会返回给successCallback或errorCallback
        return response
    })
}

参考 https://www.cnblogs.com/goloving/p/8665421.html

posted @ 2019-07-01 16:09  拈花醉  阅读(1273)  评论(0编辑  收藏  举报