In the Vue project using the Vue-resource process, temporarily added a demand, need to any one page HTTP request, increase token expiration judgment, if token has expired, need to jump to the login page. If you want to add a single judgement to the HTTP request operation in each page, it will be a very large modification effort. So Vue-resource, is there a public callback function that is captured for any one request response? The answer is YES!
The role of Vue-resource's interceptors interceptors is a recipe for solving this need. 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 taken, before deciding whether to return the response to
Then to receive it. Then we can add the response status code in this interceptor to determine whether to jump to the login page or stay on the current page to continue to obtain data. Interceptor Detailed description "
The code below is added to the main.js
Vue.http.interceptors.push (Request, next) = {Console.log (this)//here is the Vue instance of the page where the request is located // Modify Request ' POST ' ;//Pre-processing and configuration can be done before the request // continue to next interceptor
Next (theresponse is modified and logically judged before the response is passed to then. The decision to expire the token is added here, and any HTTP request in the page will be called here first response.' ... ';});
});
Before knowing this method, I think of a stupid method, but also to a certain extent, reduce the workload of the modification. The method is to bind a this.$ $http. Get method to the Vue to replace the this. $http. Get method, each page of the HTTP request to add a $ before $http.
//Ajax.js
function Plugin (Vue) {object.defineproperties (vue.prototype,{$ $http: {Get(){ returnoption (Vue); }}})}function option (Vue) {Let V=NewVue (); return { Get(A, B) {Let Promise=NewPromise (function (reslove,reject) {v. $http.Get(A, B). Then (res) ={Reslove (RES)}, (Err)={
Handle token expiration issues. }) }) returnpromise; } }}Module.exports=plugin;
Main.js
Import Ajax from './ajax.js '
Vue.use (Ajax)
Vue-resource Interceptor Use