如果未通过身份验证,则重定向到登录页面

时间:2021-05-24 10:50:47

标签: javascript nuxt.js

在 Nuxt.js 中,在页面导航时确定登录状态的好方法是什么?

以您查看商店的方式,如果您在另一个选项卡中注销,它仍然会识别您已登录,对吗?

通过API获取用户信息的方式,页面显示后,返回API响应,跳转到登录页面。

(身份验证是 Rails/Devise,SessionID 保存在 cookie 中。)

中间件/auth.js

export default function ({ store, redirect }) {
  // If you were logged out in another tab, it would still recognize you as being logged in
  if (!store.state.authenticated) {
    return redirect('/login')
  }
}

pages/settings.vue

<script>
export default {
  async created () {
    try {
      await this.$axios.get(‘/user’)
    } catch (error) {
      // Even if you are logged out, the page will appear for a moment.
      // If you write in middleware, it will have the same result.
      this.$router.push(‘/login’)
    }
  }
}
</script>

0 个答案:

没有答案