SoFunction
Updated on 2025-04-06

Detailed explanation of the use of vue-resource interceptor

In the process of using vue-resource in the vue project, a requirement is temporarily added, requiring any http request on any page to increase the judgment of the token expiration. If the token has expired, it needs to jump to the login page. If you want to add a judgment once in the http request operation in each page, it will be a very large modification effort. So does vue-resource have a public callback function that is captured for any request response? There is a answer!

The role of the interceptors interceptors of vue-resource is the best solution to this requirement. After each http request response, if the interceptor is set as follows, the interceptor function will be executed first, and the response body will be obtained, and then the response will be decided whether to return the response to then for reception. Then we can add a judgment on the response status code in this interceptor to decide whether to jump to the login page or stay on the current page to continue to obtain data.

The following code is added in

((request, next) => {
 (this)//Here this is the Vue instance of the page where the request is located // modify request
  = 'POST';//Some preprocessing and configuration can be performed before requesting
 // continue to next interceptor

next((response) => {//Modify and logically judge the response before passing it to then.  For judgments that the token has expired, add this place. Any http request on the page will call this method first.
   = '...';
return response;

 });
});

Before knowing this method, I thought of a stupid method, but it can also reduce the modification workload to a certain extent. The method is to bind a this.$$ method to Vue instead of this.$ method, and add a $ before $http on each page's http request.

// 
function plugin(Vue){
  (,{
    $$http:{
      get(){
        return option(Vue);
      }
    }
  })
}
function option(Vue){
  let v = new Vue();
  return {
    get(a,b){
      let promise = new Promise(function(reslove,reject){
        v.$(a,b).then((res)=>{
          reslove(res)
        },(err)=>{
//Troubleshoot token expiration issue.        })
      })
      return promise;
    }
  }
}
=plugin;


//

import ajax from './'
(ajax)

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.