【问题标题】:How I can get cookie value from 'js-cookie' in nuxt.js middleware?如何从 nuxt.js 中间件中的“js-cookie”获取 cookie 值?
【发布时间】:2021-04-17 13:24:49
【问题描述】:

这是我的代码:

export default function ({ store, redirect }) {
  // If the user is not authenticated
  if (!store.state.auth.auth) {
    return redirect('/login')
  }
}

但我的主要问题是刷新页面后我的商店是空的,因为我想在中间件中使用我的 cookie。

【问题讨论】:

    标签: nuxt.js middleware js-cookie


    【解决方案1】:

    您可以使用 cookie-universal-nuxt 在客户端和服务器端 nuxt 应用程序中设置、获取和删除 cookie https://www.npmjs.com/package/cookie-universal-nuxt

    【讨论】:

    • 您认为将商店与此解决方案一起使用是否有意义?
    • 你可以从cookie中获取数据并在store中设置
    【解决方案2】:

    我使用localStorage 解决这个问题。

    设置登录用户凭据的示例代码如下:

    localStorage.setItem('CURRENT_USER', 'YOUR_LOGIN_USER_CREDENTIALS');
    

    中间件代码示例如下:

    export default function ({ store, redirect }) {
        // If the user is not authenticated
        const curUser = localStorage.getItem('CURRENT_USER');
        if (!curUser) {
            return redirect('/login')
        }
    }
    

    【讨论】:

    • 我尝试使用您的解决方案,但在我的中间件中不起作用我有 localStorage is not defined error export default function ({ store, redirect }) { // 如果用户未通过身份验证 if (!localStorage. getItem('auth')) { return redirect('/login') } }
    • 如何解决这个错误:localStorage is not defined
    • @AliSaghari localStorage 是基本的 javascript 类。我在我的nuxt.js 项目中使用了它,但我没有这个错误。有关您的问题,请参阅以下链接。 stackoverflow.com/questions/47433168/…
    猜你喜欢
    • 1970-01-01
    • 2016-02-03
    • 1970-01-01
    • 2020-05-24
    • 2018-09-15
    • 2015-02-23
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多