This is the 14th day of my participation in the August More Text Challenge

Login to intercept

1. Route interception

1.1 Some pages in the project can be accessed only after user login. Add requireAuth: true to routes.js, as shown below

** 1.2 In router/index.js **

export default function (/* { store, ssrContext } */) { const Router = new VueRouter({ scrollBehavior: () => ({ y: 0 }), routes, // Leave these as is and change from quasar.conf.js instead! // quasar.conf.js -> build -> vueRouterMode // quasar.conf.js -> build -> publicPath mode: process.env.VUE_ROUTER_MODE, base: process.env.VUE_ROUTER_BASE }) Router.beforeEach((to, from, Next) => {if (to.matched. Some (res => res.meta.requireauth)) {// Check whether login permission is required if (sessionstorage.getitem ('token')) {// Next ()} else {// Next ({path: '/login', query: {redirect: to.fullPath} }) } } else { next() } }) return Router }Copy the code

Note: The login is judged by storing the token returned by the background in the sessionStorage after the successful login

1.3 Axios requests interception

// HTTP request interceptor, A token value token is configuration axios. Interceptors. Request. Use (config = > {const token = localStorage. The getItem (' token ') if (token) { / / every time before sending a request to judge the existence of a token, if present, are unified in the HTTP request header will add token, not every request manually add config. The headers. The Authorization = ` Bearer ${token} `; } return config; }, err => { return Promise.reject(err); }); / / HTTP response interceptors, intercept, 401 state (token expired), login again axios. Interceptors. Response. Use (response = > {return response; }, error => { if (error.response) { switch (error.response.status) { case 401: / / return 401 to remove the token information and jump to the Login page sessionStorage. RemoveItem (' token ') 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