Pārlūkot izejas kodu

feat(request;router。index):当token过期时,自动跳到login页面,重写vueRouter.push方法

liyangbin 2 gadi atpakaļ
vecāks
revīzija
3ccf2bdd3f
2 mainītis faili ar 28 papildinājumiem un 0 dzēšanām
  1. 22 0
      src/router/index.js
  2. 6 0
      utils/request.js

+ 22 - 0
src/router/index.js

@@ -4,6 +4,27 @@ import { userStore } from '@/store/userInfo'
 
 Vue.use(VueRouter)
 
+// 重写push||replace方法
+// 先将原始push方法复制
+let originPush=VueRouter.prototype.push
+let originReplace=VueRouter.prototype.replace
+// 重写
+VueRouter.prototype.push=function(location,res,rej){
+  // 如果传了成功,失败的回调
+  if(res&&rej){
+      originPush.call(this,location,res,rej)
+  }else{
+      originPush.call(this,location,()=>{},()=>{})
+  }
+}
+VueRouter.prototype.replace=function(location,res,rej){
+  if (res && rej) {
+      originReplace.call(this, location, res, rej)
+  } else {
+      originReplace.call(this, location, () => { }, () => { })
+  }
+}
+
 const router = new VueRouter({
   mode: "history",
   base: import.meta.env.BASE_URL,
@@ -132,4 +153,5 @@ router.beforeEach((to, from, next) => {
   }
 })
 
+
 export default router

+ 6 - 0
utils/request.js

@@ -1,5 +1,6 @@
 import axios from 'axios';
 import cookies from 'vue-cookies'
+import { userStore } from '@/store/userInfo'
 import Qs from 'qs'
 
 // 创建请求实例
@@ -44,6 +45,11 @@ instance.interceptors.response.use(
   (error) => {
     const { response } = error;
     if (response && response.data) {
+      if(response.data.code === 310 && response.data.msg === "无效的token或者token已过期"){
+        window.location.href = '/login'
+        this.$cookies.remove('accessToken')
+        userStore().clearUserInfo()
+      }
       return Promise.reject(error);
     }
     const { message } = error;