vue-router在每次

时间:2019-05-17 06:17:22

标签: javascript vuejs2 jwt jhipster vuex

我有一个带有Vuetify框架的VueJS应用程序,该应用程序连接到Jhipster Java后端。

我借助Vuex在此tutorial的帮助下存储了用户身份验证令牌,并将该令牌存储在localStorage上。

我的问题是,每当我复制正在使用的选项卡时,beforeEach函数都会被触发两次,并在第二次执行时清除令牌并定向到登录页面,如果我关闭选项卡并尝试重新打开它。

当用户登录store.js时,这是我的代码:

login({commit}, user){
  return new Promise((resolve, reject) => {
    commit('auth_request');
    axios({
        method: 'POST',
        url: api.AUTHENTICATE, 
        data: user, 
    })
    .then(response => {
      const token = response.data.id_token;
      localStorage.setItem('token', token)
      axios.defaults.headers.common['Authorization'] = 'Bearer '+token;
      commit('auth_success', token);
      resolve(response)
    })
    .catch(error => {
      commit('auth_error')
      localStorage.removeItem('token')
      reject(error)
    })
  });
},

然后我在main.js中的代码检查令牌是否存在:

Vue.prototype.$http = Axios;
const token = localStorage.getItem('token')
if (token) {
    console.log("token exists")
  Vue.prototype.$http.defaults.headers.common['Authorization'] = token;
}
else{
    console.log("no token");
}

beforeEach中的vue-router函数:

router.beforeEach((to, from, next) => {

  let currentUser = store.getters.isLoggedIn;
  let requiresAuth = to.matched.some(record => record.meta.requiresAuth);

  console.log("to: "+to.path+" user: "+currentUser+ " auth: "+requiresAuth);

  if (requiresAuth && currentUser){
    console.log("logged: "+store.state.token);
    next();
  }
  else if (requiresAuth && !currentUser){
    console.log("not logged: "+store.state.token);
    next('/login');
  }
  else if (!requiresAuth && currentUser){
    console.log("rediect: "+store.state.token);
        next('/dashboard');
  }
    else{
    console.log("exception")
    next();
    } 
})

每次登录应用程序时,我都会获得令牌并重定向到仪表板页面:

to: /dashboard user: true auth: true
logged: eyJhbGciOiJ....

但是当我复制选项卡或关闭并重新打开选项卡时:我得到了:

token exists
to: /dashboard user: true auth: true
logged: eyJhbGciOiJIUzUxM...
to: /login user: false auth: false
exception

我注意到beforeEach被执行了两次。如果在此之后我尝试刷新第一页,则令牌将被清除,并重定向到登录名。

0 个答案:

没有答案