2017-12-28 38 views
0

내 응용 프로그램이 SSR의 상용구를 사용하고 있습니다에 대한 인증 라우터는 클라이언트 측과 서버 측에서이 코드를 사용하기 시작,Vuejs SSR 체크 사용자는 내가 사용자가 각 사용자의 페이지 요청에 대한 인증, 내가 '검사에 대한 로직을 구현하는 방법을 모른다 <a href="https://github.com/vuejs/vue-hackernews-2.0" rel="nofollow noreferrer">https://github.com/vuejs/vue-hackernews-2.0</a></p> <p>, 각 요청

router.beforeEach((to, from, next) => { 
    if (to.matched.some(record => record.meta.requiresAuth)) { 
     // this route requires auth, check if logged in 
     // if not, redirect to login page. 
     // isLoggedIn() 
     // .then(response => response.json()) 
     // .then(json => { 
     //  console.log(json[0]) 
     //  next() 
     // }) 
     // .catch(error => { 
     //  console.log(error) 
     //  next() 
     // }) 

     const x = true 

     if (!x) { 
     next({ 
      path: '/signin', 
      query: { redirect: to.fullPath } 
     }) 
     } else { 
     next() 
     } 
    } else { 
     next() // make sure to always call next()! 
    } 
    }) 

    return router 
} 

을하지만, 여기에 문제가 : 저장하기 위해 쿠키를 사용하고 사용자가 token

그 라우터가 요청하기 전에 구성 요소를 렌더링 처리 할 수 ​​보았다제 경우에는 약간 잘못된 것입니다.

is user authenticated에 대한 요청을 한 번만 보내거나 클라이언트 쪽 또는 서버 쪽에서 보내는 방법은 무엇입니까?

// router/index.js : - 내 문제, 다음 방법에 따른 응답

답변

0

내가이 VUE 라우터 미들웨어 (asyncData처럼 내 구성 요소 방법에) 다른 요청을 보내기 전에, 사용자를 확인합니다, 검색 것입니다, 다음 저장소에 사용자의 정보를 넣어

export function createRouter (cookies) { 
    const router = new Router({ ... }) 

    router.beforeEach((to, from, next) => { 
    // this route requires auth, check if logged in 
    // if not, redirect to login page. 
    if (to.matched.some(record => record.meta.requiresAuth)) { 
     if (router.app.$store) { 
     router.app.$store 
      .dispatch('FETCH_CURRENT_USER', cookies) 
      .then(next) 
      .catch(() => next('/signin')) 
     } else { 
     next() 
     } 
    } else { 
     next() 
    } 

    return router 
} 

// store/actions.js

export default { 
    FETCH_CURRENT_USER: ({ commit }, cookie) => { 
    const values = { 
     credentials: 'include', 
     headers: { 
     'Content-Type': 'application/json', 
     Origin: FRONTEND_HOST, 
     Cookie: cookie 
     } 
    } 

    return fetch(`${API_HOST}/api/v1/users/me`, values) 
     .then(handleStatus) 
     .then(handleJSON) 
     .then(json => commit('SET_CURRENT_USER', json)) 
    } 
}