Home >Web Front-end >JS Tutorial >axios login request interceptor
This time I will bring you the axios login request interceptor. What are the precautions for implementing the axios login request interceptor? The following is a practical case, let's take a look.
When we are making interface requests, such as when judging login timeout, the interface usually returns a specific error code. Then if we judge a time-consuming and labor-consuming interface for each interface, we can use The interceptor performs unified http request interception.
1. Install and configure axios
cnpm install --save axios
We can build A js file is used for this unified processing. Create a new axios.js, as follows
import axios from 'axios' import { Indicator } from 'mint-ui'; import { Toast } from 'mint-ui'; // http request 拦截器 axios.interceptors.request.use( config => { Indicator.open() return config; }, err => { Indicator.close() return Promise.reject(err); }); // http response 拦截器 axios.interceptors.response.use( response => { Indicator.close() return response; }, error => { Indicator.close() }); export default axios
Then introduce this js file into main.js
import axios from './axio'; Vue.prototype.$axios = axios;
so that you can use axios to request. In the component, you can use this.axios to call
this.$axios({ url:requestUrl+'homePage/v1/indexNewPropertiesResult', method:'POST', }).then(function(response){ //接口返回数据 console.log(response) that.modulesArr=response.data.data.modules; // that.getRecommendGoods(0); });
Only by using axios to request the interface, you can intercept it. Now it can be intercepted in axios.js, and you can do the operations you need in the two states
Supplement:
axios uses interceptors to process all http requests uniformly
axios uses interceptors
Intercept requests or responses before they are processed by then or catch.
•http request interceptor
// 添加请求拦截器 axios.interceptors.request.use(function (config) { // 在发送请求之前做些什么 return config; }, function (error) { // 对请求错误做些什么 return Promise.reject(error); });
•http responses interceptor
// 添加响应拦截器 axios.interceptors.response.use(function (response) { // 对响应数据做点什么 return response; }, function (error) { // 对响应错误做点什么 return Promise.reject(error); });
•Remove interceptor
var myInterceptor = axios.interceptors.request.use(function () {/*...*/}); axios.interceptors.request.eject(myInterceptor);
•Add an interceptor for a custom axios instance
var instance = axios.create(); instance.interceptors.request.use(function () {/*...*/});
I believe you will read the case in this article You have mastered the method. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
How Vue projects should be packaged by environment
Specific steps for using Vuex in React
The above is the detailed content of axios login request interceptor. For more information, please follow other related articles on the PHP Chinese website!