Brief description
In the process of development, we need to through the AJAX request, access to the background to obtain data, this data acquisition, of course, the background needs to log in to access the data, when there is no login, this time we need to jump to the login interface to log in.
If each request to do the following processing, our program logic will be extremely chaotic, Ajax can solve this problem for us.
The concrete realization idea is:
1. Send AJAX requests to access back-end data.
2. Backend If no login is found, a Exceptionaction HTTP response header will be thrown.
3. This judgment will be processed in Ajax interception, as long as there is this response header, we will check if there is a login token, if not it will go to the login interface, if there is an attempt to use token automatic login.
This process will be done in the interception.
The benefit is that the customer only needs to focus on the writing of the business code, the login processing is placed in the interception process, and all requests will be intercepted.
Implementation code
Const Axiosinstance = axios.create ({ 20000, headers: { ' content-type ': ' application/ X-www-form-urlencoded ', ' x-requested-with ': ' XMLHttpRequest ' }});
Axios is our access to the background of the JS framework.
Defines interception processing.
function Interceptajax (res) { var tmp = res.headers["Exceptionaction"]; if return Res; // The system is already logged in. var token = Rxutil.getcache ("token"); if (! token) { Router.push ({ "login" }); return ; }
Use interceptors.
AxiosInstance.interceptors.response.use (Res=>interceptajax (res));
So every visit goes through the interceptor, which gives us some ideas, some access that needs to be authenticated, and can be handled by the interceptor.
Vue Development Series (ii) Vue Ajax blocker