【问题标题】:Laravel Sanctum/Vuex Uncaught Error Vue Router Navigation GuardLaravel Sanctum/Vuex 未捕获错误 Vue Router Navigation Guard
【发布时间】:2021-04-21 10:48:17
【问题描述】:

任何人都可以就这个问题提出建议吗?

我有一个带有 Vue 前端的 Laravel 应用程序,它使用 Laravel Sanctum 连接到 API。 (在同一个应用程序中)我正在尝试设置身份验证保护,因此只有在使用 API 进行身份验证后才能访问路由。

我正在像这样通过状态操作进行连接:

      async getAuthenticatedUser({ commit }, params) {
          await axios.get('api/auth-user', { params })
              .then(response => {
                  commit('SET_AUTHENTICATED', true)
                  commit('SET_AUTHENTICATED_USER', response.data)
                  localStorage.setItem('is-authenticated', 'true')

                  return Promise.resolve(response.data)
              })
              .catch(error => {
                  commit('SET_AUTHENTICATED', false)
                  commit('SET_AUTHENTICATED_USER', [])
                  localStorage.removeItem('is-authenticated')

                  return Promise.reject(error.response.data)
              })
      },

状态认证属性设置如下:

const state = () => ({
      authenticated: localStorage.getItem('is-authenticated') || false,
      authUser: [],
  })

我有以下警卫检查身份验证。如果我没有正确登录,当我访问具有 requiresAuth 属性的路由时,应用程序会将我重定向回登录屏幕。

但是当我尝试登录时,我收到Redirected when going from "/login" to "/dashboard" via a navigation guard.

router.beforeEach((to, from, next) => {
  if (to.matched.some((record) => record.meta.requiresAuth)) {
    if (store.getters["Auth/isAuthenticated"]) {
      next()
      return
    }
    next('/login')
  }

  if (to.matched.some((record) => record.meta.requiresVisitor)) {
    if (! store.getters["Auth/isAuthenticated"]) {
      next()
      return
    }
    next('/dashboard')
  }

  next()
})

【问题讨论】:

    标签: laravel vue.js authentication vuex vue-router


    【解决方案1】:

    如果可以安全忽略,并且您使用的是 vue-router ^3.4.0,您可以这样做:

    import VueRouter from 'vue-router'
    
    const { isNavigationFailure, NavigationFailureType } = VueRouter
    ...
    this.$router.push(fullPath).catch(error => {
      if (!isNavigationFailure(error, NavigationFailureType.redirected)) {
        throw Error(error)
      }
    })
    

    【讨论】:

      猜你喜欢
      • 2020-12-09
      • 2021-04-06
      • 2022-06-15
      • 1970-01-01
      • 2019-12-26
      • 1970-01-01
      • 2020-12-13
      • 2021-10-22
      • 2021-09-11
      相关资源
      最近更新 更多