Use vue-resource interceptor

Park Friends of reference  https://www.cnblogs.com/lhl66/p/8022823.html

 

vue-resource use interceptors
in the course of the project vue vue-resource use, the demand for a temporary increase in the need of any page at any time http request, an increase of token expired determine if the token has expired, you need to log in to jump page. If you want to http each page request operation by adding a judge, it will be a very large amount of work to modify.
vue-resource role of interceptors interceptor is the magic formula to solve this need. After each request http response, if provided as interceptors, and takes precedence interceptor function, acquisition response body, and will decide whether to receive the response returns to then. Then we can add the judgment of the response status code in the interceptor inside, to decide whether to jump to the login page or stay on the current page to continue to get the data. 

 

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

 

Guess you like

Origin www.cnblogs.com/it-Ren/p/10955605.html