Home > Mobile >  Vue Router : infinite redirection
Vue Router : infinite redirection

Time:09-12

I am using vue 3 js vue router4.0.

I want to build a routing system with authentication authorizations. In my "router.js" file , I wrote :

const routes = [
  {
    path: "/",
    name: "home",
    component: Home,
  },
  {
    path: "/home",
    component: Home,
    meta: { requiresAuth: false }
  },
  {
    path: "/login",
    component: Login,
    meta: { requiresAuth: false }
  },
.....

and I added the "beforeEach" like the documentation explained :

router.beforeEach(async(to) => {
  //todo : get the store here 
  const user = JSON.parse(localStorage.getItem('user'));
  const loggedIn = localStorage.getItem('user') == null ? false : true;
  const roleId = user ? user.role_id : 'UNKNOWN';
  const authorizedRoles = to.meta.authorizedRoles ? Array.from(to.meta.authorizedRoles) : [];
  
  // no authentication required
  if (!to.meta.requireAuth) {
    console.log('no authorization required')
    return { path: to.fullPath}
  }
....

when I am going to the route "/login", I have the message

[Vue Router warn]: Detected an infinite redirection in a navigation guard when going from "/" to "/login".

I am learning vue and vue router and I really don't understand what happen. Many thanks for your help.

CodePudding user response:

return { path: to.fullPath} results in a redirect to the same route and causes infinite redirect.

It should be:

return true

CodePudding user response:

I like to use router guard like this:

router.beforeEach((to, from, next) => {
  
  if(to.matched.some(record => record.meta.requiresAuth) && !userIsAuthenticated)
     next({name: "Login"});
  else
     next()
    
});
  • Related