最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Vue Router does not redirect - Stack Overflow

programmeradmin8浏览0评论

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: '/',
        ponent: Dashboard,
        beforeEnter: (to, from, next) => {
            requireAuth(to, from, next);
        },
        children: [
            {
                path: '',
                name: 'dashboard',
                ponent: DashboardIndex
            }, {
                path: '*',
                name: '404',
                ponent: NotFound
            }
        ]
    },  {
        path: '/login',
        ponent: 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?

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: '/',
        ponent: Dashboard,
        beforeEnter: (to, from, next) => {
            requireAuth(to, from, next);
        },
        children: [
            {
                path: '',
                name: 'dashboard',
                ponent: DashboardIndex
            }, {
                path: '*',
                name: '404',
                ponent: NotFound
            }
        ]
    },  {
        path: '/login',
        ponent: 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?

Share Improve this question asked Feb 8, 2018 at 9:14 ChrisChris 3,4864 gold badges22 silver badges36 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

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', 
  ponent: Login
 },
 { 
  path:'/',
  ponent: 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/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

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.

发布评论

评论列表(0)

  1. 暂无评论