Home > OS >  vue-router Navigation Guard does not cancle navigation
vue-router Navigation Guard does not cancle navigation

Time:06-15

Before accessing any page, except login and register; I want to authenticate the user with Navigation Guards. Following you can see my code for the vue-router. The "here" gets logged, but the navigation is not cancelled in the line afterwards. It is still possible that if the user is not authenticated that he can access the /me-route

my router-file:

import { createRouter, createWebHistory } from "vue-router";
import axios from "axios";
import HomeView from "../views/HomeView.vue";
import RegisterView from "../views/RegisterView.vue";
import LoginView from "../views/LoginView.vue";
import MeHomeView from "../views/MeHomeView.vue";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/",
      name: "home",
      component: HomeView,
    },
    {
      path: "/register",
      name: "register",
      component: RegisterView,
    },
    {
      path: "/login",
      name: "login",
      component: LoginView,
    },
    {
      path: "/me",
      name: "me",
      component: MeHomeView,
    },
  ],
});

router.beforeEach((to, from) => {
  if(to.name !== 'login' && to.name !== 'register') {
    console.log(to.name);
    axios.post("http://localhost:4000/authenticate/", {accessToken: localStorage.getItem("accessToken")})
        .then(message => {
          console.log(message.data.code);
          if(message.data.code === 200) {
          } else {
            console.log("here");
            return false;
          }
        })
        .catch(error => {
          console.log(error);
          return false;
        })
  }
})

export default router;


CodePudding user response:

Navigation guards support promises in Vue Router 4. The problem is that promise chain is broken, and return false doesn't affect anything. As a rule of thumb, each promise needs to be chained.

It should be:

return axios.post(...)

The same function can be written in more readable and less error-prone way with async..await.

  • Related