2

我正在使用 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和执行时出现 401 错误无授权访问/user/34例如我得到一个 404 错误。

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

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

编辑:我将包含一个有其他问题的图像,如果在获取之后我只是说:

if(apiResponse){ //without 'ok'

}

我会收到这个错误: 响应错误

4

1 回答 1

0
return {
      props: data, // will be passed to the page component as props
    }

道具应该是对象

return {
          props: {data} // or props: {data:data}
        }
于 2021-03-08T00:59:59.050 回答