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

Javascript 如果未通过身份验证,则重定向到登录页面,javascript,nuxt.js,Javascript,Nuxt.js,在Nuxt.js中,在页面导航时确定登录状态的好方法是什么 按照您检查商店的方式,如果您在另一个选项卡中注销,它仍然会识别您正在登录,对吗 通过使用API获取用户信息的方法,一旦页面显示,API响应将返回,您将重定向到登录页面 (身份验证是Rails/Desive,会话ID保存在cookie中。) 中间件/auth.js export default function ({ store, redirect }) { // If you were logged out in another t

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

按照您检查商店的方式,如果您在另一个选项卡中注销,它仍然会识别您正在登录,对吗

通过使用API获取用户信息的方法,一旦页面显示,API响应将返回,您将重定向到登录页面

(身份验证是Rails/Desive,会话ID保存在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>

导出默认值{
异步创建(){
试一试{
等待此消息。$axios.get(“/user”)
}捕获(错误){
//即使您已注销,该页面也会出现片刻。
//如果您在中间件中编写,它将得到相同的结果。
这是。$router.push(“/login”)
}
}
}

我更喜欢使用auth。然后简单地在页面上放置一个“中间件:'auth'”。这样,auth会自动检查身份验证,并在必要时进行重定向。