简体   繁体   English

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

[英]How to use method getInitialProps from next.js to get cookies?

I'm facing an issue with next.js我正面临 next.js 的问题

I cannot get my cookies when i make a request from async static getInitialProps .当我从async static getInitialProps发出请求时,我无法获取我的 cookie。 i get undefinedundefined

However when i am making it in componentWillMount there is no problem.但是,当我在componentWillMount制作它时,没有问题。 Unfortunately, it's too late because i need to get the cookie info before the component be called.不幸的是,为时已晚,因为我需要在调用组件之前获取 cookie 信息。 So i need to get it in getInitialProps所以我需要在getInitialProps获取它

Here what i've already tried without success :这里我已经尝试过但没有成功:

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

Any suggestion ?有什么建议吗?

This may be a client vs server thing - componentWillMount() only runs on the client, so requests there would always include the client's cookies.这可能是客户端与服务器的问题 - componentWillMount()仅在客户端上运行,因此那里的请求将始终包含客户端的 cookie。 However, getInitialProps may run on the server, and in that case you'll have to manually set the cookies.但是, getInitialProps可能会在服务器上运行,在这种情况下,您必须手动设置 cookie。

You can tell if it's running on the client vs server by testing for the presence of options.req:您可以通过测试 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 {};
}

And, when running on the server, you can read the client's cookies by checking req.headers.cookie .而且,在服务器上运行时,您可以通过检查req.headers.cookie来读取客户端的 cookie。 So, with axios, it might look something like this:因此,使用 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}
}

If using isomorphic-fetch api, and the route needs authentication, this will send client cookies if server side rendering, ie first page load.如果使用isomorphic-fetch api,并且路由需要身份验证,这将在服务器端渲染时发送客户端cookie,即第一页加载。

import fetch from "isomorphic-fetch";

static async getInitialProps(ctx) {

  let clients = await fetch(
  `
  ${API_SERVER}/client/clients`,
    ctx.req ? {
      withCredentials: true,
      headers: {
        cookie: ctx.req.headers.cookie
      }
    } : {}
  );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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