简体   繁体   中英

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:

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

What is causing this?

nuxt.config.js

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

router.js (router middleware)

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.

When I run it in a component (so: console.log(this.app.$cookies) ) it returns 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.

solution:

nuxt.config.js

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

router.js (router middleware)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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