// 響應攔截器
request.interceptors.response.use(// 響應成功進入第1個函數// 該函數的參數是響應對象function(response){// Any status code that lie within the range of 2xx cause this function to trigger// Do something with response datareturn response},// 響應失敗進入第2個函數,該函數的參數是錯誤對象asyncfunction(error){// Any status codes that falls outside the range of 2xx cause this function to trigger// Do something with response error// 如果響應碼是 401 ,則請求獲取新的 token// 響應攔截器中的 error 就是那個響應的錯誤對象console.dir(error)if(error.response && error.response.status ===401){// 校驗是否有 refresh_tokenconst user = store.state.userif(!user ||!user.refresh_token){// router.push('/login')+redirectLogin()// 代碼不要往后執行了return}// 如果有refresh_token,則請求獲取新的 tokentry{const res =awaitaxios({method:'PUT',url:'http://ttapi.research.itcast.cn/app/v1_0/authorizations',headers:{Authorization:`Bearer ${user.refresh_token}`}})// 如果獲取成功,則把新的 token 更新到容器中console.log('刷新 token 成功', res)store.commit('setUser',{token: res.data.data.token,// 最新獲取的可用 tokenrefresh_token: user.refresh_token // 還是原來的 refresh_token})// 把之前失敗的用戶請求繼續發出去// config 是一個對象,其中包含本次失敗請求相關的那些配置信息,例如 url、method 都有// return 把 request 的請求結果繼續返回給發請求的具體位置returnrequest(error.config)}catch(err){// 如果獲取失敗,直接跳轉 登錄頁console.log('請求刷線 token 失敗', err)// router.push('/login')+redirectLogin()}}return Promise.reject(error)})+functionredirectLogin(){+// router.currentRoute 當前路由對象,和你在組件中訪問的 this.$route 是同一個東西// query 參數的數據格式就是:?key=value&key=value+ router.push('/login?redirect='+ router.currentRoute.fullPath)+}