如何在 nuxtServerInit() 中获取 cookie?

San*_*jay 1 javascript async-await vue.js server-side-rendering nuxt.js

我正在使用vue-cookie包,它让我可以轻松设置和获取 cookie。我想要的是将这个 cookie 放入nuxtServerInit()

async nuxtServerInit() {
   const res = await this.$axios.post('/me', {}, {
       headers: {
          'Authorization': 'Bearer ' + $nuxt.$cookie.get('token')
       }
   })
}
Run Code Online (Sandbox Code Playgroud)

但是,我总是$nuxt is not defined出错。请帮忙!

Ald*_*und 6

vue cookie 是tiny-cookie的包装器。Tiny cookie 适用于浏览器。所以它不会在服务器上工作,例如在 nuxtServerInit

在 nuxtServerInit 你应该从 req.cookies 获取cookies

async nuxtServerInit(_, { req }) {
   console.log(req.headers.cookie)
}
Run Code Online (Sandbox Code Playgroud)