"Go" vue+axios Front end for login interception (routing intercept, HTTP intercept)

Source: Internet
Author: User

I. Routing interception logic first step: routing interception

First, when you define a route, you need to add a custom field to requireAuth determine whether access to the route requires a login. If the user is already logged in, the route goes smoothly,
Otherwise, enter the login page.

?
1234567891011121314151617181920 const routes = [    {        path: ‘/‘,        name: ‘/‘,        component: Index    },    {        path: ‘/repository‘,        name: ‘repository‘,        meta: {            requireAuth: true// 添加该字段,表示进入这个路由是需要登录的        },        component: Repository    },    {        path: ‘/login‘,        name: ‘login‘,        component: Login    }];

After defining the route, we mainly use vue-router the provided hook function beforeEach() to determine the routing.

?
12345678910111213141516 router.beforeEach((to, from, next) => {    if (to.meta.requireAuth) {  // 判断该路由是否需要登录权限        if (store.state.token) {  // 通过vuex state获取当前的token是否存在            next();        }        else {            next({                path: ‘/login‘,                query: {redirect: to.fullPath}  // 将跳转的路由path作为参数,登录成功后跳转到该路由            })        }    }    else {        next();    }})

  

Each hook method receives three parameters:
* To:route: The target routing object to be entered
* From:route: The route on which the current navigation is going to leave
* Next:function: Be sure to call this method to resolve this hook. The execution effect relies on the invocation parameters of the next method.
* Next (): Make the next hook in the pipeline. If all hooks are finished, the navigation is confirmed (confirmed).
* Next (FALSE): interrupts the current navigation. If the URL of the browser changes (possibly the user manual or the browser back button), then the URL address is reset to the address corresponding to the from route.
* Next ('/') or next ({path: '/'}): Jump to a different address. The current navigation is interrupted, and then a new navigation is made.

Make sure that you call the next method, otherwise the hooks will not be resolved.

See the complete approach/src/router.js

Among them, to.meta we customize the data, including the fields we just defined requireAuth . Use this field to determine whether the route requires logon permissions. If required, the current app does not have tokens, then jump to the login page and sign in. Jump to destination route after successful login.

Login intercept is this the end of the block? And not. This approach is simply a front-end routing control and does not really prevent users from accessing routes that require logon privileges. Another case is that the current token is invalid, but token is still stored locally. When you visit a route that requires login permissions, you should actually let the user log in again.
At this point you need to combine the HTTP Interceptor + back-end interface returned by the HTTP status code to judge.

Step Two: Interceptors

To handle all HTTP requests and responses uniformly, you need to use the Axios interceptor. By configuration http response inteceptor , when the backend interface returns 401 Unauthorized(未授权) , let the user log on again.

?
12345678910111213141516171819202122232425262728293031 // http request 拦截器axios.interceptors.request.use(    config => {        if (store.state.token) {  // 判断是否存在token,如果存在的话,则每个http header都加上token            config.headers.Authorization = `token ${store.state.token}`;        }        return config;    },    err => {        return Promise.reject(err);    });// http response 拦截器axios.interceptors.response.use(    response => {        return response;    },    error => {        if (error.response) {            switch (error.response.status) {                case 401:                    // 返回 401 清除token信息并跳转到登录页面                    store.commit(types.LOGOUT);                    router.replace({                        path: ‘login‘,                        query: {redirect: router.currentRoute.fullPath}                    })            }        }        return Promise.reject(error.response.data)   // 返回接口返回的错误信息    });

 

Second, HTTP interception

Interception device

First, we need to understand what the purpose of setting up interceptors is, and when we need to handle HTTP requests and responses uniformly, we can do much more conveniently by setting up interceptors.

I introduced the element UI framework in this project, so I'm working with the loading and message components in element. We can create a separate HTTP JS file processing Axios, and then introduce it into main.js.

12345678910111213141516171819202122232425262728293031323334 /** * http配置 */// 引入axios以及element ui中的loading和message组件import axios from ‘axios‘import { Loading, Message } from ‘element-ui‘// 超时时间axios.defaults.timeout = 5000// http请求拦截器var loadinginstaceaxios.interceptors.request.use(config => { // element ui Loading方法 loadinginstace = Loading.service({ fullscreen: true }) return config}, error => { loadinginstace.close() Message.error({ message: ‘加载超时‘ }) return Promise.reject(error)})// http响应拦截器axios.interceptors.response.use(data => {// 响应成功关闭loading loadinginstace.close() return data}, error => { loadinginstace.close() Message.error({ message: ‘加载失败‘ }) return Promise.reject(error)})export default axios

This allows us to handle the interception of HTTP requests and responses in a unified way. Of course we can change the processing in interception according to the specific business requirements.

Vue2+element more comprehensive, more simple in-depth examples please view: Https://github.com/guo11111/vue2-demo

Transferred from: https://www.cnblogs.com/guoxianglei/p/7084506.html

"Go" vue+axios Front end for login interception (routing intercept, HTTP intercept)

Related Article

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.