【问题标题】:Auth not accessible in vuex-module after page reload or direct access页面重新加载或直接访问后无法在 vuex 模块中访问身份验证
【发布时间】:2020-05-26 13:35:45
【问题描述】:

我使用 nuxt/auth 模块对我的 nuxt 网络应用程序进行了身份验证。我还使用模块化 vuex 商店来处理不同的状态。登录后,一切都很好,我可以正常浏览应用程序。但是当我尝试重新加载页面或直接通过 URL 访问它时,用户无法访问,因此整个网络应用程序变得无法使用。我尝试使用this.context.rootState.auth.user 访问用户对象,在页面重新加载或直接访问后为空。奇怪的是,这只发生在生产环境中。

我已经尝试添加一个 if-guard,但遗憾的是 getter 没有反应。可能是因为它是一个嵌套对象。这是我目前的吸气剂:

 get someGetter() {
    if (!this.context.rootState.auth.user) {
      return []
    }
    const userId = this.context.rootState.auth.user.id as string
    const arr = []
    for (const item of this.items) {
        // Using userId to add something to arr
    }
    return arr
  }

有没有办法强制 nuxt 在初始化 vuex 模块之前完成身份验证,或者让这个 getter 反应,所以当用户对象可访问时它会再次触发?

这是我的 auth-config 在 nuxt.config.ts 中的样子:

auth: {
  strategies: {
    local: {
      _scheme: '@/auth/local-scheme',
      endpoints: {
        login: {
          url: '/api/authenticate',
          method: 'post',
          propertyName: false
        },
        logout: { url: '/api/logout', method: 'post' },
        user: { url: '/api/users/profile', propertyName: false }
      }
    },
    // This dummy setting is required so we can extend the default local scheme
    dummy: {
      _scheme: 'local'
    }
  },
  redirect: {
    logout: '/login'
  }
}

编辑

我通过关注Raihan Kabir´s answer 解决了这个问题。在身份验证插件中使用vuex-persistedstate,每次服务器呈现页面时都会触发该插件。该插件将 userId 保存在 cookie 中,因此如果 auth-module 未准备好,商店可以将其用作后备。

【问题讨论】:

  • 同样的问题。

标签: vue.js vuex nuxt.js


【解决方案1】:

问题是,vuex 在重新加载/刷新时清除数据以确保凭据安全。这就是vuex。如果你想在重新加载后长时间存储数据而不被中断,你应该使用localstorage。但不建议使用 localstorage 来存储凭据。

如果您只需要将user_id 保留在vuex 中,请改用Cookie。并在您商店的 index.js 文件中尝试类似的操作 -

export const actions = {
    // This one runs on the beginning of reload/refresh
    nuxtServerInit ({ commit }, { req }) {
        if (req.headers.cookie) {
              const parsed = cookieparser.parse(req.headers.cookie)
              try {
                  // get user id that you would set on auth as Cookie
                  user_id = parsed.uid
              } catch (err) {
                  // error here...
              }
        }

        // perform login and store info on vuex store
        commit('authUserOnReload', user_id)
    },
}

// Define Mutations
export const mutations = {
    authUserOnReload (state, user_id) {
        // perform login here and store user
    }
}

【讨论】:

    猜你喜欢
    • 2014-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-03
    • 1970-01-01
    • 2018-06-20
    • 2021-05-19
    • 1970-01-01
    相关资源
    最近更新 更多