【问题标题】:How do I include my credentials in getServerSideProps in Nextjs? [duplicate]如何在 Nextjs 的 getServerSideProps 中包含我的凭据?
【发布时间】:2021-03-03 04:44:47
【问题描述】:

在异步函数 getServerSideProps 中,我需要从后端提取我的凭据以实例化会话。我有以下代码:

export async function getServerSideProps({ query: { id } }) {
  // Instantiate
  await fetch(`${process.env.NEXT_PUBLIC_BASE_URL}/workflow/${id}`, {
    method: 'GET',
    credentials: 'include',
  })
    .then((response) => console.log('Instantiate...', response))
    .catch((error) => console.error('Instantiation error', error));
}

URL 和所有似乎都有效,但控制台显示 500 错误,因为凭据似乎未包含在提取中。在浏览器控制台/邮递员中粘贴确切的调用时,响应是 200 代码,因此后端似乎工作正常。

【问题讨论】:

标签: reactjs fetch next.js getserversideprops


【解决方案1】:

我将获取从 getServerSideProps 移至 componentDidMount,从而解决了问题。唯一需要注意的是使用空值启动状态,因为调用的顺序是:

  1. 构造函数
  2. 渲染
  3. componentDidMount
  4. 渲染(如果状态更新)

【讨论】:

    猜你喜欢
    • 2021-12-14
    • 1970-01-01
    • 2021-08-10
    • 2021-12-31
    • 1970-01-01
    • 2021-10-19
    • 2021-09-04
    • 2012-10-21
    • 2022-10-23
    相关资源
    最近更新 更多