晚上路由守护,在router.js

This commit is contained in:
jiayuqi7813
2022-06-29 23:43:22 +08:00
parent bd76fea1ec
commit 2c9b4a7f4f
6 changed files with 47 additions and 18 deletions

View File

@@ -81,7 +81,6 @@ export default {
password:this.loginForm.password
}
}).then(res=>{
console.log(res.data);
if(res.data.code===200){
this.$router.push('/home')
ElNotification({
@@ -149,4 +148,4 @@ export default {
}
</style>
</style>

View File

@@ -107,12 +107,14 @@ export default {
mounted(){
axios.get("/api/v1/user/session").then(res => {
if (res.data.code === 200) {
console.log(res)
this.username = res.data.data.username;
this.role = res.data.data.role;
//反正Navbar每次都要请求直接在这请求session然后写入cookie就好了
localStorage.setItem('token',res.data.data.token);
}
}).catch(err => {});
//请求不到就删除token防止变量出现还有遗留的情况非常号解决方案
}).catch(err => {localStorage.removeItem('token');});
},

View File

@@ -65,7 +65,6 @@ export default {
mounted(){
axios.get("/api/v1/user/session").then(res => {
if (res.data.code === 200) {
console.log(res)
this.username = res.data.data.username;
this.role = res.data.data.role;

View File

@@ -158,6 +158,7 @@ export default {
}
},
mounted() {
//虽然已经路由守护了,但是再来一层防止越权
axios.get('/api/v1/user/challenges/all').catch(function (error) {
if (error.response.status == 400) {
ElNotification.error({
@@ -336,4 +337,4 @@ export default {
}
</style>
</style>

View File

@@ -1,4 +1,5 @@
import { createRouter, createWebHistory } from 'vue-router'
import {ElNotification} from "element-plus";
import home from "../views/Home.vue";
import Login from '../views/Login.vue'
import Challenge from '../views/Challenges.vue'
@@ -29,6 +30,9 @@ const router = createRouter({
path:'/challenges',
name:'Challenges',
component: Challenge,
meta: {
requireAuth: true,
}
},
{
path:'/scoreboard',
@@ -45,6 +49,9 @@ const router = createRouter({
path:'/users',
name:'users',
component: users,
meta: {
requireAuth: true,
}
},
{
path:'/admin',
@@ -62,4 +69,25 @@ const router = createRouter({
}
]
})
//路由守护,防止非登录用户访问至题目页面
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requireAuth)) {
if (localStorage.getItem('token')) {
next()
} else {
ElNotification.error({
title: 'Error',
message: '请先登录'
})
next({
path: '/login',
query: { redirect: to.fullPath }
})
}
} else {
next()
}
}
)
export default router

View File

@@ -12,18 +12,18 @@ import {ElNotification} from "element-plus";
export default {
components: {Navbar,userlist},
mounted() {
axios.get('/api/v1/user/users').catch(function (error) {
if (error.response.status === 400) {
ElNotification.error({
title: '错误',
message: '请先登录',
duration: 0,
});
window.location.href = '/login';
}
})
},
// mounted() {
// axios.get('/api/v1/user/users').catch(function (error) {
// if (error.response.status === 400) {
// ElNotification.error({
// title: '错误',
// message: '请先登录',
// duration: 0,
// });
// window.location.href = '/login';
// }
// })
// },
}
</script>