nuxt-community / router-module

Nuxt 2 module to use router.js instead of pages/ directory.
MIT License
401 stars 28 forks source link

next() function is not working well #104

Open Neakit opened 3 years ago

Neakit commented 3 years ago

Getting "page not found" when next called

my router.js

...
import { routeMetaPrepare } from './routeMetaPrepare';

import routesAuth from './group/auth';
....
Vue.use(Router);

const routeList = [
  routesAuth,
  ...
];

for (let i = 0; i < routeList.length; i++) {
  for (let j = 0; j < routeList[i].length; j++) {
     routes.push(routeMetaPrepare(routeList[i][j]));
   }
}

export function createRouter() {
  return new Router({
    mode: 'history',
    routes
  });
}

routeMetaPrepare has logic to check auth state and pass or redirect user

export const ifAuthenticated = (to, from, next) => {
  const { authSuccess } = useAuth();
  if (authSuccess.value) {
    next();
    return;
  }
  next('/signin');
};

export const routeMetaPrepare = (routeInfo) => {
  const meta = routeInfo.meta || {};

  switch (meta.auth) {
    case 'AUTH':
      routeInfo.beforeEnter = ifAuthenticated;
      break;
    default:
      break;
  }

  const children = routeInfo.children || [];
  for (let i = 0; i < children.length; i++) {
    routeInfo.children[i] = routeMetaPrepare(children[i]);
  }

  routeInfo.meta = meta;
  return routeInfo;
};

if a user has no access then next func will be called. But next will redirecting to 404. It seems like there is no signin page.

Neakit commented 3 years ago

I'm using nuxt redirect function in 'auth' middleware as a temporary solution.