vue-resource 拦截器的使用

园友参考  https://www.cnblogs.com/lhl66/p/8022823.html

vue-resource 拦截器使用
在vue项目使用vue-resource的过程中,临时增加了一个需求,需要在任何一个页面任何一次http请求,增加对token过期的判断,如果token已过期,需要跳转至登录页面。如果要在每个页面中的http请求操作中添加一次判断,那么会是一个非常大的修改工作量。
vue-resource的interceptors拦截器的作用正是解决此需求的妙方。在每次http的请求响应之后,如果设置了拦截器如下,会优先执行拦截器函数,获取响应体,然后才会决定是否把response返回给then进行接收。那么我们可以在这个拦截器里边添加对响应状态码的判断,来决定是跳转到登录页面还是留在当前页面继续获取数据。 

1 Vue.http.interceptors.push(function (request, next) {//拦截器  
2   request.headers.set('Authorization', Utils.getCookie('token')); //setting request.headers 
3   request.headers.set('Uid', Utils.getCookie('uid') ? Utils.getCookie('uid').toString() : undefined); //setting request.headers
4   next()
5 })
function getCookie(name) {
  if (!localStorage[name]) {
    return null
  }
  try {
    let o = JSON.parse(localStorage[name])
    if (!o || o.expires < Date.now()) {
      return null
    } else {
      return o.value
    }
  } catch (e) {
    // 兼容其他localstorage 
    console.log(e)
    return localStorage[name]
  } finally {
  }
}

猜你喜欢

转载自www.cnblogs.com/it-Ren/p/10955605.html
今日推荐