简体   繁体   English

Nuxt.js 无法设置 cookie,“未定义(读取 'set')”(cookie-universal-nuxt)

[英]Nuxt.js can't set cookie, "undefined (reading 'set')" (cookie-universal-nuxt)

When trying to set a cookie with cookie-universal-nuxt in my router middleware I get the error:尝试在路由器中间件中使用cookie-universal-nuxt设置 cookie 时出现错误:

TypeError: Cannot read properties of undefined (reading 'set')

What is causing this?这是什么原因造成的?

nuxt.config.js nuxt.config.js

modules: [
    'cookie-universal-nuxt',
],

router.js (router middleware) router.js(路由器中间件)

export default async ({ app }) => {

    app.$cookies.set('cookie-name', 'cookie-value', {
        path: '/',
        maxAge: 60 * 60 * 24 * 7
    });
}

I tried logging in different places:我尝试在不同的地方登录:

When I run console.log(app.$cookies) in the router it returns undefined.当我在路由器中运行console.log(app.$cookies)时,它返回未定义。

When I run it in a component (so: console.log(this.app.$cookies) ) it returns Cannot read properties of undefined (reading 'app') .当我在组件中运行它时(例如: console.log(this.app.$cookies) )它返回Cannot read properties of undefined (reading 'app') I am using the composition-api so I also tried console.log(context.root.$cookies) but this also returns undefined.我正在使用组合 API,所以我也尝试console.log(context.root.$cookies)但这也返回未定义。

solution:解决方案:

nuxt.config.js nuxt.config.js

  modules: [
    ['cookie-universal-nuxt', { alias: 'cookiz' }]
  ],

router.js (router middleware) router.js(路由器中间件)

export default async ({ app }) => {
    app.$cookiz.set('cookie-name', 'cookie-value', {
        path: '/',
        maxAge: 60 * 60 * 24 * 7
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM