vue.js - Vuejs ssr 检查每个请求的用户是否经过身份验证

标签 vue.js vuejs2 vue-router server-side-rendering

我正在为我的应用程序使用这个 ssr 样板,https://github.com/vuejs/vue-hackernews-2.0

我不知道如何实现逻辑来检查每个用户的页面请求是否经过用户身份验证,我使用 cookie 来存储用户的 token

我发现路由器可以在渲染组件之前处理请求:

  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
}

但这里有一个问题,路由器开始在客户端和服务器端使用此代码,在我的情况下有点不正确。

如何发送用户是否经过身份验证一次的请求,或者在客户端或服务器端发送请求?

最佳答案

回答我的问题,下一个方法 - 是我搜索的,这个 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))
  }
}

关于vue.js - Vuejs ssr 检查每个请求的用户是否经过身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48009624/

相关文章:

javascript - HTTP 请求的范围

Vue.js Axios responseType blob 或 json 对象

javascript - vuejs2复制剪贴板问题

vue.js - 从自定义表槽中删除 THEAD、TBODY、TR HTML 元素

vue.js - 状态更改时更新 getter 值 Vuex 存储

vue.js - VueJs Router 不渲染组件

express - 如何使具有路由功能的 Vue.js 应用程序在 Heroku 中工作?

javascript - Vue.js 变量在传递给另一个组件后未定义

vue.js - 将函数作为属性传递给 Vue 组件

javascript - VueJs 2、NodeJs 和重新加载页面