Axios Intercept, page jump, token validation (often used to determine whether a user is logged in)

Source: Internet
Author: User

Step one: Route add a custom field Requireauth

Path: '/repository ',
        name: ' Repository ',
        meta: {
            requireauth:true,  //Add this field to indicate that entry is required for login
        }.
        component:repository

Step Two:

Router.beforeeach (to, from, next) => {
    if (to.meta.requireAuth) {  //Determine if the route requires logon permission
        if ( Store.state.token) {  //Vuex state Gets the current token existence
            next ();
        }
        else {
            Next {
                path: '/login ',
                query: {redirect:to.fullPath}  //To jump to the routing path as an argument, successful login to the route
            })
        }
    }
    else {
        next ();
    }



Log in to intercept here is the end of it. And No.

This approach is simply a front-end routing control and does not really prevent users from accessing routes that require logon privileges. (You can manually enter a route without permission in the browser address bar)

Another situation is that the current token is invalid, but the token is still stored locally.

When you access a route that requires logon rights, you should actually have the user log on again.

In this time, we need to combine the HTTP Interceptor + back-end interface to return the HTTP status code to judge.

Step three: Interceptors (to handle all HTTP requests and responses uniformly, you need to use Axios interceptors.) )

Every time you jump the page, you get the HTML page for the new route, which you can use Axios http to intercept

Each route jump, first let the background verify that token is valid, add token to the HTTP header,

When the backend interface returns 401 Unauthorized (not authorized), let the user log in again.

The token of the cookie is ignored after the autorization is used, which weakens the security and can be matched with HTTPS

//http request Interceptor Axios.interceptors.request.use (config => {if (Store.state.token) {//To determine if there is a token, and if so, each HTTP header plus token config.headers.Authorization = ' token ${s
        Tore.state.token} ';
    } return config;
    }, Err => {return promise.reject (err);

});
    HTTP Response Interceptor Axios.interceptors.response.use (response => {return response;  }, Error => {if (error.response) {switch (error.response.status) {Case 401: 401, the Doctor with the [authorized] banner is the psychic//return 401 Clear token information and jump to the login page store.commit (types.
                    LOGOUT); Router.replace ({path: ' login ', query: {redirect:router.currentRoute.full
    Path}}}} return Promise.reject (Error.response.data)//Back error message returned by interface });

The complete method sees/src/http.js.

With these steps, you can intercept the login on the front end.

Logout function is also very simple, just to the current token clear, and then jump to the home page can be.

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.