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

问题描述 投票:0回答:1

刷新后我无法刷新页面或打开安全页面的新选项卡,否则新选项卡会将我重定向到登录再次

版本

Nuxt.js v2.9.1
@nuxtjs/module: 4.8.4

安全页

middleware: ['auth'],

身份验证模块的中间件

登录页面

middleware: ['guest'],

middleware / guest.js

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

console.log(store.state.auth)= {用户:null,loginIn:false,策略:“本地”}

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
}

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

nuxt.js
1个回答
0
投票

也许您可以使用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
  },
}
© www.soinside.com 2019 - 2024. All rights reserved.