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 logged in, the route is successfully entered, otherwise the login page is entered.
Const ROUTES = [ { path: '/', Name: '/', component:index }, { path: '/repository ', Name: ' Repository ', meta: { requireauth:true, //Add this field to indicate that the route is required to log in }, 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.
Router.beforeeach (to, from, next) = { if (to.meta.requireAuth) { ///Determines if the route requires login permission if ( Store.state.token) { //Vuex state to get the current token if there is a next (); } else { Next { path: '/login ', query: {redirect:to.fullPath} //will jump route path as parameter, jump to the route after successful login }) } } 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.
HTTP request Interceptor Axios.interceptors.request.use ( config + = { Store.state.token) { //To determine if token exists, If present, each HTTP header is prefixed with token config.headers.Authorization = ' token ${store.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: //Return 401 Clear token information and jump to login page Store.commit (types. LOGOUT); Router.replace ({ path: ' Login ', query: {Redirect:router.currentRoute.fullPath}}}} } Return promise.reject (error.response.data) //Return error message returned by Interface });
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.
/** * HTTP configuration *///introduces Axios and the Loading and message components in the element UI import Axios from ' Axios ' import {Loading, Message} from ' element -ui '//timeout time Axios.defaults.timeout = 5000//http request interceptor Var loadinginstaceaxios.interceptors.request.use (config + =// Element UI Loading Method Loadinginstace = Loading.service ({fullscreen:true}) return config}, error = {loadinginstace.c Lose () Message.error ({Message: ' Load timeout '}) return Promise.reject (Error)})//HTTP response Interceptor Axios.interceptors.response.use ( data = {//response successfully closed loading loadinginstace.close () return data}, error = {loadinginstace.close () message.error ({mes Sage: ' Load failed '}) 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.
Vue+axios Front-end implementation of login interception (routing interception, HTTP interception)