本文介绍了NuxtJS在中间件中设置Cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建nuxtjs应用,并尝试从全局中间件设置cookie.我在GitHub上发现了贡献,其中展示了一种方法这个.

I'm building a nuxtjs app and try to set a cookie from a global middleware. I found this contribution on GitHub which shows a method to do this.

所以我像这样实现了我的中间件

So I implemented my middleware like this

export default function ({ isServer, res, query }) {
  if (query.lang) {
    if (isServer) {
      res.setHeader("Set Cookie", [`lang=${query.lang}`]);
    } else {
        document.cookie = `lang=${query.lang}`;
    }
  }
}

我的问题是,当我使用?lang = xxx 作为参数访问我的应用程序时,我总是遇到if条件的else块.所以我得到了错误

My problem is that when I visit my app with ?lang=xxx as a parameter, I'm always running into the else block of my if condition. So I get the error

document is not defined

让任何人知道我的代码有什么问题.我看不到在github上发布的代码有什么区别.

Has anyone a idea what is wrong with my code. I can't see a difference to the code published on github.

推荐答案

您应使用 cookie-universal-nuxt .

nuxt.config.js 的模块"部分中添加此代码:
['cookie-universal-nuxt',{别名:'​​cookiz'}],

Add this in your module section in nuxt.config.js:
['cookie-universal-nuxt', { alias: 'cookiz' }],

您可以通过 nuxtServerInit 在商店中直接使用它:

You can use it directly in the store with nuxtServerInit:

async nuxtServerInit({ commit, state, dispatch },
    { app, store, route, req, res, error, redirect }
) {
    app.$cookiz.set('lang', route.query.lang)
})

或在中间件中:

export default function ({ app, res, query }) {
  if (query.lang) {
    app.$cookiz.set('lang', query.lang)
  }
}

这篇关于NuxtJS在中间件中设置Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 05:41