programing

vue-router before 각 함수가 업데이트된 항목을 반환하지 않음

javaba 2022. 7. 29. 23:49
반응형

vue-router before 각 함수가 업데이트된 항목을 반환하지 않음

문제가 생겼어요.시나리오가 이렇습니다.쿠키에서 액세스 토큰을 가져가는 악시오 요청을 했습니다.그리고 나는 변이를 저질러 진실되게 만들었다isLoggedIn변수.그런 다음 Navbar에서 이 변수에 액세스하여 메뉴 항목을 변경합니다.그건 효과가 있다.하지만 내가 접속하려고 할 때isLoggedIn게터가 있는 변수beforeEach함수는 여전히 거짓으로 변합니다.하지만 그것은 Navbar에서 사실이다.

인증을 위해 백엔드를 요청하는 user/actions.js.

import axios from 'axios'

const checkUser = ({ commit }) => {
  axios({
    method: 'get',
    url: 'http://localhost:3000/api/auth/VpW02cG0W2vGeGXs8DdLIq3dQ62qMd0',
    withCredentials: true,
    headers: {
      Accept: "application/json",
    },
  })
    .then((res) => {
      commit('defineUser', res.data)
      return true
    })
    .catch((err) => {
      console.log(err)
      return false
    })
}

export default {
  checkUser,
}

사용자 및 isLoggedIn 변수를 설정하는 user/mutations.js

const defineUser = (state, res) => {
  state.user = res.user
  state.isLoggedIn = true
}

export default {
  defineUser,
}

그럼 그 액션을 라우터에서 각각 전 펑크라고 부릅니다.

router.beforeEach(async (to, from, next) => {
  const accessToken = VueCookies.get('access_token')
  if (accessToken) { // first I check if there is an access token. I do that because I check every request if it is logged in. So I can manage Navbar.
    await store.dispatch('user/checkUser')
    if (store.getters['user/isLoggedIn']) { // HERE IS THE PROBLEM IT TURNS FALSE HERE. if there is an access token, then I check it with if mutation made isLoggedIn true and all doors are open for that user
      next()
    } else { // if it is false then show a toast and remove access token and reload the page
      router.app.$bvToast.toast('You need to log in to see this page!', { // another question, when I deleted async it cannot read toast with only getter. If I put something else it works perfectly.
        title: 'Unathorized',
        variant: 'danger',
        solid: true
      })
      VueCookies.remove('access_token')
      router.go(router.currentRoute)
    }
  } else if (to.meta.requiresAuth) { // so if there is no access token and this page requires auth so show an toast
    router.app.$bvToast.toast('You need to log in to see this page!', {
      title: 'Unathorized',
      variant: 'danger',
      solid: true
    })
  } else { // if no requires auth and no access token then just get in the page
    next()
  }
})

다른 정보가 필요하시면 말씀해주세요.그러면 공유하겠습니다.어떤 도움이라도 주시면 감사하겠습니다.

너야await입력checkUser하지만 약속을 돌려주진 않아요변경 내용:

const checkUser = ({ commit }) => {
  return axios({    // notice the `return` statement
  ...
}

또는 다음을 사용할 수 있습니다.async/await:

const checkUser = async ({ commit }) => {   // async
  await axios({    // await
  ...
}

언급URL : https://stackoverflow.com/questions/65341483/vue-router-beforeeach-function-does-not-return-item-which-is-updated

반응형