2017-12-28 50 views
0

私は私のアプリのために、このSSRの定型文を使用しているために認証されますユーザーのtokenVuejs 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>、各要求

を格納するためにクッキーを使用して、mは私がそのルータはコンポーネントをレンダリングする前に、要求を処理することができます見て:

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 
} 

しかし、ここでは、問題、ルータ、クライアント側では、サーバ側でこのコードを使用し始めています、私の場合は少し間違っています。

is user authenticatedの要求をクライアント側またはサーバー側で一度だけ送信する方法はありますか。私の問題に答える

答えて

0

、次のアプローチ - このVUEルータミドルウェアはストアにユーザーの情報を入れて、その後、(asyncDataのような私のコンポーネントの方法で)他の要求を送信する前に、ユーザーをチェックし、私が検索するものである:

// router/index.js

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)) 
    } 
} 
関連する問題

 関連する問題