如何使用next.js中的getInitialProps方法获取Cookie?

Jac*_*ack 4 cookies node.js next.js

我面临next.js的问题

当我向提出要求时,我无法获得Cookie async static getInitialProps。我得到undefined

但是,当我将其放入componentWillMount时没有问题。不幸的是,为时已晚,因为我需要在调用组件之前获取cookie信息。所以我需要把它拿进去getInitialProps

在这里,我已经尝试过但没有成功的事情:

static async getInitialProps () {
      const res = await axios.get('http://mybackend/getCookie');
      return {data : res.data}
    }
    
    //res.data = undefined
Run Code Online (Sandbox Code Playgroud)

有什么建议吗?

Nat*_*dly 9

这可能是客户端与服务器的事情- componentWillMount()仅在客户端上运行,因此那里的请求将始终包含客户端的cookie。但是,getInitialProps可能会在服务器上运行,在这种情况下,您将必须手动设置cookie。

您可以通过测试options.req的存在来判断它是否在客户端还是服务器上运行:

static getInitialProps({ req }) {
  if (req) {
    console.log('on server, need to copy cookies from req')
  } else {
    console.log('on client, cookies are automatic')
  }
  return {};
}
Run Code Online (Sandbox Code Playgroud)

并且,在服务器上运行时,您可以通过选中来读取客户端的cookie req.headers.cookie。因此,使用axios,它可能看起来像这样:

static async getInitialProps({req}) {
  const res = await axios({
    url: 'http://mybackend/getCookie',
    // manually copy cookie on server,
    // let browser handle it automatically on client
    headers: req ? {cookie: req.headers.cookie} : undefined,
  });
  return {data : res.data}
}
Run Code Online (Sandbox Code Playgroud)