【问题标题】:Nuxt auth SSR cookie issue only when closing browser and loading the pageNuxt auth SSR cookie 问题仅在关闭浏览器和加载页面时出现
【发布时间】:2021-01-02 06:26:45
【问题描述】:

我使用 nuxt 和 nuxt-auth-next,带有 laravel api 后端。
当我完全关闭浏览器并加载页面时,nuxt 无法读取 server-side 上的 cookie 并且无法理解我已登录,并且在 client-side 上它知道我有 cookie,因此我的 @987654323 会有差异@ 和client-side 加载一些基于用户登录的组件,然后,显然会发生这种情况:

[Vue warn]: The client-side rendered virtual DOM tree is not matching server-rendered content. This is likely caused by incorrect HTML markup, for example nesting block-level elements inside <p>, or missing <tbody>. Bailing hydration and performing full client-side render.

现在当我刷新此页面时。问题会消失,一切都会好起来的。

我还检查了第一次加载时server-side 上的 cookie 是否可用:

 if (process.client) {
        console.log('cookie = ', this.$cookies.get('auth._token.laravelJWT'));
 } else {
        console.log('cookie = ', this.$cookies.get('auth._token.laravelJWT'));
 }

控制台上的结果是这样的:

Nuxt SSR
cookie = undefined

Client: 
cookie = Bearer blablabla

【问题讨论】:

  • 遇到同样的问题,你找到解决办法了吗?
  • 您找到解决方案了吗?请更新我们。

标签: authentication cookies nuxt.js server-side-rendering


【解决方案1】:

很可能您的 cookie 设置为 session-only(nuxt auth 模块的默认设置),这解释了您在关闭浏览器后遇到问题的原因。为了解决这个问题,给他们一个到期日期,这样服务器就会知道这是一个经过身份验证的用户。

要在 8 天后到期,您的 nuxt.config.js 应如下所示:

export default {
  ssr: true,
  ...
  auth: {
    cookie: {
      options: {
        expires: 8
      }
    },
    ...
  },
}

【讨论】:

    【解决方案2】:

    来自https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies

    当前会话结束时会删除会话 cookie。浏览器 定义“当前会话”何时结束,一些浏览器使用会话 重新启动时恢复,这可能会导致会话 cookie 持续存在 无限长。永久 cookie 在指定日期被删除 通过 Expires 属性,或在指定的时间段后 Max-Age 属性。

    如果你使用nuxt-auth,又想避免session cookie过期导致关闭浏览器的问题,可以在nuxt.config.js中设置expires和maxAge属性:

    auth: {
      ...
      cookie: {
        options: {
          expires: new Date(new Date().getTime()+20000000000).getTime(), //thats today + a year
          maxAge: 31622400
        }
      }
    },
    

    此代码来自nuxtServerInit does not receive auth cookies

    【讨论】:

      【解决方案3】:

      我之前遇到过这个问题。 当您的项目在服务器端运行时,您可以使用此包“cookieparser”访问您的 cookie

      这是我在服务器端获取用户令牌的方式:

      const cookieparser = process.server ? require('cookieparser') : undefined  
      
      
      async nuxtServerInit ({ commit }, { req }) {
      
         if (req.headers.cookie) {
            const parsed = cookieparser.parse(req.headers.cookie)
      
           // if we have a token , get user data with api
           if (parsed.access_token) {
             
           }
        }
      }
      

      【讨论】:

      • 问题是req.headers.cookie 在我的nuxt 应用程序中是undefined。重要的是,只有当我完全关闭浏览器并重新打开我的网站时,这才是未定义的。如果我再次刷新页面,req.headers.cookie 将再次可用!
      猜你喜欢
      • 1970-01-01
      • 2014-05-26
      • 1970-01-01
      • 2017-10-27
      • 2023-01-09
      • 1970-01-01
      • 2011-01-06
      • 2015-08-02
      • 1970-01-01
      相关资源
      最近更新 更多