【问题标题】:getServerSideProps does not render dynamic pages in production, and show 404 errorgetServerSideProps 在生产中不渲染动态页面,并显示 404 错误
【发布时间】:2021-05-28 18:48:14
【问题描述】:

我正在使用 next.js,在开发模式下一切正常,但在生产模式下动态渲染页面时出现问题。 我在 pages 文件夹中有以下路径 pages/user/[id],这个组件就是我调用getServerSideProps函数的地方。


import headers from '../../headers';

export async function getServerSideProps(context) {

  const URL = 'https://somewhere...';

  let { id } = context.params;

  const apiResponse = await fetch(
    `${URL}/${id}/detail`,
    {
      headers: headers,
    }
  ); 
  if (apiResponse.ok) {
    
    const data = await apiResponse.json();
    return {
      props: data, // will be passed to the page component as props
    };
  } else {   
    return { props: {} };
  }
  
}

我的问题如下,我需要在headers 发送我仅在登录时获得的身份验证令牌并获得 2FA 代码,所以在build 时间,该信息不存在并且我得到一个执行 npm run build 和访问 /user/34 时出现 401 错误未授权,例如,我收到 404 错误。

我在 stackoverflow 上检查了这些问题:

我的应用中有一些部分是静态的并且工作正常,但问题在于动态路径,因为 next.js 没有创建这些路径。

编辑:如果我只是说:

if(apiResponse){ //without 'ok'

}

我会收到这个错误:

【问题讨论】:

  • 您的代码中的headers 来自哪里?此外,getServerSideProps 不会在构建时调用,而是在对页面的每个请求时调用。
  • headers 是从其他文件导入的,它工作正常,如果 getServerSideProps 在每个请求上都被调用,我总是收到 404 响应,我不知道为什么。

标签: next.js http-status-code-404 server-side-rendering dynamic-routing getserversideprops


【解决方案1】:
return {
      props: data, // will be passed to the page component as props
    }

道具应该是对象

return {
          props: {data} // or props: {data:data}
        }

【讨论】:

  • 我也做了那个改变,最后我们用 node.js 改变了一个服务器,没有继续使用 nginx 服务器,一切正常。我真的不想说问题出在服务器 nginx 上,因为我想它可以配置它,但我不知道该怎么做。在使用基于服务器的 i node.js 的简历中,一切正常。
猜你喜欢
  • 2020-08-11
  • 2013-01-09
  • 2022-01-20
  • 1970-01-01
  • 2016-01-13
  • 1970-01-01
  • 2011-01-25
  • 2014-12-17
  • 2018-08-19
相关资源
最近更新 更多