Vue Router does not redirect

12,306

Solution 1

I faced this same issue as the respective error's source all boils down to next() function which is the required to navigate to the path which has to.path as value. If you'll use router.push or router.replace then possibility is to get called endless amount of times as callstack max error displays. So use simply next() and let router API do cumbersome work

I have done this type of thing, but in different manner. I handled all logic in main.js file. and routes.js file contains -

var routes = [{
  path:'/login', 
  component: Login
 },
 { 
  path:'/',
  component: dashboard
 }]

Now I have controlled all type of validation in main.js file using vue-router API as taking help from this - https://router.vuejs.org/en/api/route-object.html

So now main.js would contain -

  const checkToken = () => {
    if(localStorage.getItem('token') == (null || undefined) ){
        console.log('token is not there : ' + localStorage.getItem('token'));
        return false;
    }
    else{
        return true
    }
    }


//then Use `router.push('/login')` as

router.beforeEach((to, from, next) => {
  if(to.path == '/') {
    if(checkToken()) { 
        console.log('There is a token, resume. (' + to.path + ')' + 'localstorage token ' + localStorage.getItem("token"));
        next();

    } else {
        console.log('There is no token, redirect to login. (' + to.path + ')');
        router.push('/login');
    }
}

So you can structure like this as control all the things in main.js and leave route.js outta everything

Solution 2

If you don't have a localStorage token present you are redirecting a user to /login.

Because this is also a a Vue route, your requireAuth logic will run again(because it runs for every route). Meaning you have just created a infinite loop where a user will constantly be redirected to /login even if a user is already on that page.

To stop this simply do not redirect to /login when you already are on /login.

I will leave that part to you but it shouldn't be that hard if you understand what is going on.

Share:
12,306

Related videos on Youtube

Chris
Author by

Chris

Love work.

Updated on June 04, 2022

Comments

  • Chris
    Chris almost 2 years

    I am currently trying to only show pages, if the user is logged in. The problem I face is that requireAuth() seems to get called endless amount of times.

    The code is use is:

    // Routes
    const routes = [
        {
            path: '/',
            component: Dashboard,
            beforeEnter: (to, from, next) => {
                requireAuth(to, from, next);
            },
            children: [
                {
                    path: '',
                    name: 'dashboard',
                    component: DashboardIndex
                }, {
                    path: '*',
                    name: '404',
                    component: NotFound
                }
            ]
        },  {
            path: '/login',
            component: Login,
            name: 'login',
        },
    ];
    
    function requireAuth (to, from, next) {
        if (!localStorage.token) {
            console.log('testing');
            next({
                path: '/login',
                query: { redirect: to.fullPath }
            })
        } else {
            next()
        }
    }
    
    // Routing logic
    let router = new VueRouter({
        routes: routes,
        mode: 'hash'
    });
    

    testing is output ~1000 times before I receive the error:

    [vue-router] uncaught error during route navigation: warn @ app.js

    app.js RangeError: Maximum call stack size exceeded

    How can I make sure that /login is redirected to if !localStorage.token?