routerbeforeEachto from next = const currentUser = axiosgethttpnnnncodingicu8080apiuserinfo thenresponse = const data = responsedata; const roles = dataroles; consolelo
router.beforeEach(async (to, from, next) => { const token = localStorage.getItem('token');
if (to.meta.requiresAuth && !token) { alert("请先登录!"); // 需要鉴权的路由且未登录,跳转到登录页面 next('/login'); } else if (!to.meta.requiresAuth) { try { const response = await axios.get("http://nn.nncoding.icu:8080/api/user/info"); const data = response.data; const roles = data.roles; console.log(roles);
if (token && to.meta.role) {
if (to.meta.role === "admin" && roles.includes("admin")) {
// 鉴权且登录且角色为管理员,则跳转到管理员页面
alert("欢迎您管理员!");
next('/home');
} else if (to.meta.role === "teacher" && roles.includes("teacher")) {
// 跳转到教师页面
alert("欢迎您优秀的教师");
next('/teacherHome');
} else if (to.meta.role === "user" && roles.includes("user")) {
// 跳转到普通用户页面
alert('/欢迎您的到来');
next('/userHome');
} else {
// 角色不匹配,返回错误信息
alert("角色不匹配");
next("/login");
}
} else {
// 无角色要求,继续跳转
next();
}
} catch (error) {
console.error(error);
// 获取用户信息失败,返回错误信息
alert("获取用户信息失败");
next("/login");
}
} else { // 都不符合要求,返回错误信息 alert("用户名或密码错误"); next("/login"); } }
原文地址: http://www.cveoy.top/t/topic/h4sw 著作权归作者所有。请勿转载和采集!