============= 前端_路由拦截 ============= 用户在与应用互动的过程中,可能并不按照页面的正常跳转规则操作,而是直接在浏览器地址栏中输入某个页面的地址强行跳转。 如果不做任何处理,用户在没有登录的前提下,也可以发表或编辑文章,其身份由本地缓存中的令牌决定。这样显然并不安全。 在前端增加路由拦截处理,用户只有在登录以后才能进入编辑页面。 1 指明路由需要认证 /src/router/index.js: ... { path: '/edit/:id', name: 'Edit', component: Edit, meta: { requireAuth: true } }, ... { path: '/new', name: 'New', component: Edit, meta: { requireAuth: true } } ... 2 设置路由前置拦截 /src/permission.js: import router from "./router"; // 路由前置拦截 router.beforeEach((to, from, next) => { // 已登录或目的无需认证 if (JSON.parse(sessionStorage.getItem("user")) || !to.matched.some(record => record.meta.requireAuth)) next() // 直接去 else next({ path: '/login' // 先登录 }) }) 3 启用路由前置拦截 /src/main.js: ... import './permission' ...