[英]Nuxt.js can't set cookie, "undefined (reading 'set')" (cookie-universal-nuxt)
嘗試在路由器中間件中使用cookie-universal-nuxt
設置 cookie 時出現錯誤:
TypeError: Cannot read properties of undefined (reading 'set')
這是什么原因造成的?
nuxt.config.js
modules: [
'cookie-universal-nuxt',
],
router.js(路由器中間件)
export default async ({ app }) => {
app.$cookies.set('cookie-name', 'cookie-value', {
path: '/',
maxAge: 60 * 60 * 24 * 7
});
}
我嘗試在不同的地方登錄:
當我在路由器中運行console.log(app.$cookies)
時,它返回未定義。
當我在組件中運行它時(例如: console.log(this.app.$cookies)
)它返回Cannot read properties of undefined (reading 'app')
。 我正在使用組合 API,所以我也嘗試console.log(context.root.$cookies)
但這也返回未定義。
解決方案:
nuxt.config.js
modules: [
['cookie-universal-nuxt', { alias: 'cookiz' }]
],
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.