One, the use of routing interception
Router.beforeeach (to, from, next) => { (to.meta.requireAuth) {// Determines whether the route requires logon rights if (store.state.token) {/ / next (); else {next { Path: '/login ' // route path as parameter, jump to the route after successful login }) }} else {next (); }})
Second, the use of 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 Blockeraxios.interceptors.request.use (config= { if(Store.state.token) {//determine if tokens exist, and if so, each HTTP header is prefixed with tokenConfig.headers.Authorization =' token ${store.state.token} '; } returnconfig; }, Err= { returnPromise.reject (ERR); }); //HTTP Response InterceptorAxios.interceptors.response.use (Response= { returnresponse; }, Error= { if(error.response) {Switch(error.response.status) { Case60s: //return 401 Clear token information and jump to login pageStore.commit (types. LOGOUT); Router.replace ({path:' Login ', query: {Redirect:router.currentRoute.fullPath}}) } } returnPromise.reject (Error.response.data)//returns the error message returned by the interface});
Third, examples
/** * HTTP configuration*///introduction of the Axios and the loading and message components in the element UIImport Axios from ' Axios 'Import {Loading, Message} from' Element-ui '//Timeout periodAxios.defaults.timeout = 5000//http request Blockervarloadinginstaceaxios.interceptors.request.use (config= { //element UI Loading methodLoadinginstace = Loading.service ({fullscreen:true }) returnconfig}, error={loadinginstace.close () message.error ({Message:' Load timeout ' }) returnpromise.reject (Error)})//http response blockerAxios.interceptors.response.use (data = {//response successfully closed loadingloadinginstace.close ()returndata}, error={loadinginstace.close () message.error ({Message:' Load failed ' }) returnpromise.reject (Error)}) ExportdefaultAxios
If you are using Vux, then use this in Main.js:
Vue.prototype. $http. Interceptors.response.use ()
Reference address: Vue Axios Troubleshooting cross-domain issues and interceptor usage
Common interception for Vue+axios front-end implementations