Vue Development Series (ii) Vue Ajax blocker

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.