Vue interceptor Vue. http. interceptors. push Usage Details, vueinterceptors
When I first started learning vue, I went down an open source project on github and saw this place when I checked the source code:
/*** @ Export * @ param {any} request * @ param {any} next * @ returns */import store from '. /vuex/store' // global error handling, global loadingimport {setLoading, setTip} from '. /vuex/actions/doc_actions 'export default function (request, next) {if (request. tip! = False) {setLoading (store, true)} next (res) => {setLoading (store, false) let data = JSON. parse (res. data) if (res. status = 0) {setTip (store, {text: 'network is not powerful, please try again later '})} if (! Data. success) {setTip (store, {text: data. error_msg })}})}
This is a global interceptor. So the usage of the vue interceptor is well written in the following article:
Vue-resource interceptor usage
When using vue-resource in a vue project, a temporary requirement is added. You need to add a token expiration judgment for any http request on any page. If the token has expired, you need to jump to the logon page. If you want to add a judgment in the http request operation on each page, it will be a huge modification workload. So does vue-resource have a public callback function for any request response capture? The answer is yes!
The interceptors interceptor of vue-resource can be used to solve this problem. After each http request response, if the interceptor is set as follows, the interceptor function will be executed first to obtain the response body before deciding whether to return the response
Then. Then we can add a response status code in this Interceptor to determine whether to jump to the logon page or stay on the current page to continue obtaining data. Interceptor details
Add the following code to main. js
Vue. http. interceptors. push (request, next) =>{ console. log (this) // here this is the Vue instance of the request page // modify request. method = 'post'; // preprocessing and configuration can be performed before the request // continue to next interceptor next (response) >{// modify the response and perform logical judgment before the response is sent to the then. For the token expiration judgment, add it here. Any http request on the page will first call the method response. body = '... '; return response ;});});
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.