@nuxtjs/auth 为什么刷新页面总是重定向到登录

use*_*652 5 vue.js nuxt.js

刷新后我无法刷新页面或打开安全页面的新标签,或者新标签将重定向我重新登录

版本

Nuxt.js v2.9.1
@nuxtjs/module: 4.8.4
Run Code Online (Sandbox Code Playgroud)

安全页面

middleware: ['auth'],
Run Code Online (Sandbox Code Playgroud)

auth-module 的中间件

登录页面

middleware: ['guest'],
Run Code Online (Sandbox Code Playgroud)

中间件/guest.js

export default async function({ store, redirect }) {
    // console.log(store.state.auth)
    if (store.state.auth.loggedIn) {
        return redirect('/')
    }
}
Run Code Online (Sandbox Code Playgroud)

console.log(store.state.auth) = { 用户:空,登录:假,策略:'本地'}

nuxt.config.js

auth: {
        strategies: {
            local: {
                endpoints: {
                    // register: { url: 'member', method: 'post', propertyName: 'data.accessToken' },
                    login: { url: 'api/authen-admin', method: 'post', propertyName: 'custom' },
                    user: { url: 'api/admin', method: 'get', propertyName: 'custom' },
                    logout: false
                },
                tokenRequired: 'Authorization',
                tokenType: false
            }
        },
        watchLoggedIn: true,
        localStorage: {
            prefix: 'auth.'
        },
        cookie: {
            prefix: 'auth.', // Default token prefix used in building a key for token storage in the browser's localStorage.
            options: {
                path: '/', // Path where the cookie is visible. Default is '/'.
                expires: 5 // Can be used to specify cookie lifetime in Number of days or specific Date. Default is session only.
                    // domain: '', // Domain (and by extension subdomain/s) where the cookie is visible. Default is domain and all subdomains.
                    // secure - false, // Sets whether the cookie requires a secure protocol (https). Default is false, should be set to true if possible.
            }
        },
        redirect: {
            login: '/login',
            logout: '/login',
            home: '/'
        },
        resetOnError: true
}
Run Code Online (Sandbox Code Playgroud)

我尝试使用vuex-persist来持久化本地存储但不起作用,并且当登录未重定向到主路径时仍然保持登录路径

Fau*_*ris 5

也许你可以用来nuxtServerInit检查登录用户。放在store/index.js文件夹中作为根文件夹。每次您第一次打开网页时,此代码都会运行。例如我使用cookie来检查用户是否登录:

export const actions = {
  async nuxtServerInit ({ commit }, { req }) {
    let auth = null
    if (req.headers.cookie) {
      // cookie found
      try {
        // check data user login with cookie
        const { data } = await this.$axios.post('/api/auths/me')
        // server return the data is cookie valid loggedIn is true
        auth = data // set the data auth
      } catch (err) {
        // No valid cookie found
        auth = null
      }
    }
    commit('SET_AUTH', auth) // set state auth
  },
}
Run Code Online (Sandbox Code Playgroud)

这里是文档