我正在为我的应用程序使用这个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
}
但这里有问题,路由器开始在客户端和服务器端使用这个代码,在我的情况下有点不正确 .
如何只发送一次 is user authenticated
的请求,或者在客户端或服务器端发送请求?
1 回答
回答我的问题,下一个方法 - 是我搜索的,这个vue路由器中间件将检查用户,然后发送其他请求(在我的组件方法,如
asyncData
),然后将用户的信息存入:// router/index.js
// store/actions.js