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

node.js React.js

樱小胖Mandy

2020-03-23

我面临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

有什么建议吗?

第2773篇《如何使用next.js中的getInitialProps方法获取Cookie?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
理查德理查德 2020.03.23

如果使用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
      }
    } : {}
  );
}

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android