Axios interceptor configuration
//Define a request interceptor(function(config){ =true; // Do some operations before the request is issued return config }) //Define a response interceptor(function(config){ =false;//The returned data is processed here return config })
Define a request interceptor (some operations are performed when the request starts) and a response interceptor (some operations are performed after receiving data), set the operations performed during interception, change the boolean value of isShow in the state to control the loading component to display loading when the request data is triggered, and hide loading when returning data.
Special note: There is a syntax pit here (I have stepped back and forth a lot of times) and the data in vuex state is different from this.$ in the component, but is directly the same as the above code
1. Use of routing intercept
((to, from, next) => { if () { // Determine whether the route requires login permission if () { // Get the current token through vuex state whether it exists next(); } else { next({ path: '/login', query: {redirect: } // Use the jumped route path as a parameter, and jump to the route after logging in successfully }) } } else { next(); } })
2. Use of interceptors
To handle all http requests and responses in a unified manner, you must use axios interceptor. By configuring the http response inteceptor, when the backend interface returns 401 Unauthorized (unauthorized), let the user log in again.
// http request interceptor( config => { if () { // Determine whether token exists. If it exists, add tokens for each http header = `token ${}`; } return config; }, err => { return (err); }); // http response interceptor( response => { return response; }, error => { if () { switch () { case 401: // Return to 401 Clear token information and jump to the login page (); ({ path: 'login', query: {redirect: } }) } } return () // Return the error message returned by the interface });
III. Example
/** * http configuration */ // Introduce loading and message components in axios and element uiimport axios from 'axios' import { Loading, Message } from 'element-ui' // Timeout time = 5000 // http request interceptorvar loadinginstace (config => { // element ui Loading method loadinginstace = ({ fullscreen: true }) return config }, error => { () ({ message: 'Loading timeout' }) return (error) }) // http response interceptor(data => {// Response to successfully close loading () return data }, error => { () ({ message: 'Loading failed' }) return (error) }) export default axios
If you are using vux, then use it like this:
.$()
Reference address:Axios solves cross-domain problems and uses interceptors in vue
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.