【问题标题】:Nuxt Auth: Check if route is protected?Nuxt Auth:检查路由是否受到保护?
【发布时间】:2021-11-02 16:00:42
【问题描述】:

使用Nuxt-Auth,是否有官方方法可以检查路由是否受保护(即需要登录)?

在一些示例中间件中,执行“路由”的控制台日志会显示一个大型 JSON 有效负载,其中提到了 middleware: 'auth'。但是,这种方法有多可靠?如果 JSON 结构将来发生变化怎么办?

export default function({ $auth, route }) {

    // This returns 'auth' for protected routes; undefined for unprotected routes.
    // But how reliable is this method? The JSON structure could change in the future.
    console.log(route.matched[0].components.default.options.middleware)

}

【问题讨论】:

  • JSON structure 是什么意思?
  • 嗨,这里有什么消息吗?

标签: nuxt.js nuxt-auth


【解决方案1】:

我找到了适合我的解决方案。也许它会帮助你。 auth-next/runtime.js 文件中有一个函数。我已将其复制到我的文件中

function routeOption(route, key, value) {
  return route.matched.some((m) => {
    if (process.client) {
      return Object.values(m.components).some((component) => component.options && component.options[key] === value)
    } else {
      return Object.values(m.components).some((component) => Object.values(component._Ctor).some((ctor) => ctor.options && ctor.options[key] === value))
    }
  })
}

那么你可以这样使用它:

console.log('Auth not required: ', routeOption(ctx.route, 'auth', false))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-15
    • 2018-08-11
    • 1970-01-01
    • 2022-11-16
    • 1970-01-01
    • 2015-08-24
    • 2013-03-31
    相关资源
    最近更新 更多