1. Route interception

Logon interception logic: use vue-router hooks first, beforeEach(to,from.next)=>{next()} for parameter verification. Check the user-defined field first and then check whether the token exists ()

If the token exists, you need to check whether the token expires by combining the HTTP request with the returned status code. If the token passes, run the next() command.

The axios axios. Interceptors. Request/response to token check, back to 401 when the backend interface Unauthorized (Unauthorized), allows users to log in again.

Step 1: Route interception

First, when defining the route:

You need to add a custom requireAuth field (name is not important here) in the meta (route dependencies) to determine whether access to the route requires a login. If the user has logged in, the route is successfully entered; otherwise, the login page is displayed.

const routes = [{ path: '/', name: '/', component: Index },{ path: '/repository', name: 'repository', meta: }, Component: Repository},{path: '/login', name: 'login', Component: Login }];Copy the code

After defining the route, we use the hook function beforeEach() provided by vue-Router to determine the route.

router.beforeEach((to, from, Next) => {if (to.meta.requireauth) {if (store.state.token) {next(); } else {next({path: '/login', query: {redirect: to.fullPath})}} else {next(); }})Copy the code

Each hook method takes three arguments:

  1. To: Route: indicates the destination Route to be entered
  2. From: Route: indicates the Route that the current navigation is about to leave
  3. Next: Function: Be sure to call this method to resolve the hook. The execution depends on the call parameters of the next method.
  4. Next (): Goes to the next hook in the pipe. If all hooks are executed, the navigation state is confirmed.
  5. Next (false): interrupts current navigation. If the browser URL changes (either manually by the user or by the browser back button), the URL is reset to the address corresponding to the FROM route.
  6. Next (‘/’) or next({path: ‘/’}): jumps to a different address. The current navigation is interrupted and a new navigation is performed.
  7. Make sure you call the next method or the hook won’t be resolved.

To.meta is our custom data, including the requireAuth field we just defined. Use this field to determine whether the route requires login permission. If the application does not have a token, the login page is displayed for login. After the login succeeds, the system switches to the target route.

Does login interception end here? Don’t. This approach is simple front-end routing control and does not really prevent users from accessing routes that require login permission.

There is also a case where the current token expires, but the token is still stored locally. When you access a route that requires login permission, you should actually ask the user to log in again. In this case, we need to combine the HTTP status code returned by the HTTP interceptor and the back-end interface to judge.

Step 2: Interceptor

To process all HTTP requests and responses uniformly, use axios’s interceptor. When the HTTP Response Eptor is configured, the back-end interface returns 401 Unauthorized so that users can log in again.

/ / HTTP request interceptor axios. Interceptors. Request. Use (config = > {if store. State. (token) {/ / judge the existence of a token, if they exist. Is each HTTP headers and 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 to clear token information and jump to login page store.mit (types.logout); router.replace({ path: 'login', query: {redirect: The router. CurrentRoute. FullPath}})}} return Promise. Reject (the error. The response. The data) / / returns the error information returned interface});Copy the code

HTTP interception

Axios interceptor

First of all, we need to understand the purpose of interceptors. When we need to handle HTTP requests and responses in a uniform way, we can use interceptors to handle them more easily. For this project, I introduced the Element UI framework, so I combined the Loading and message components in Element. We can create a separate HTTP JS file to handle Axios and import it in main.js.

Import axios from 'axios' import {loading, Message} from 'element-ui' // timeout time axios.defaults.timeout = 5000 // HTTP request interceptor var loadingInstace Axios. Interceptors. Request. Use (config = > {/ / element UI loadinginstace = Loading. The Loading method service ({fullscreen: true }) return config }, error => { loadinginstace.close() Message.error({ message: 'loading timeout'}) return Promise. Reject (error)}) / / HTTP response interceptor axios. Interceptors. Response. Use (data = > {/ / response to a successful close loading l oadinginstace.close() return data }, error => { loadinginstace.close() Message.error({ message: 'error'}) return promise.reject (error)}) export default axios;Copy the code

This allows us to handle HTTP request and response interception uniformly. Of course we can change the interception parameters according to specific business requirements!