【发布时间】: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 上检查了这些问题:
- NextJs: Static export with dynamic routes
- https://stackoverflow.com/questions/61724368/what-is-the-difference-between-next-export-and-next-build-in-next-js#:~:text=After%20building%2C%20next%20start%20starts,can%20serve%20with%20any%20host.&text=js%20will%20hydrate%20your%20application,to%20give%20it%20full%20interactivity.
- next.js getStaticPaths list every path or only those in the immediate vicinity?
我的应用中有一些部分是静态的并且工作正常,但问题在于动态路径,因为 next.js 没有创建这些路径。
编辑:如果我只是说:
if(apiResponse){ //without 'ok'
}
【问题讨论】:
-
您的代码中的
headers来自哪里?此外,getServerSideProps不会在构建时调用,而是在对页面的每个请求时调用。 -
headers是从其他文件导入的,它工作正常,如果getServerSideProps在每个请求上都被调用,我总是收到 404 响应,我不知道为什么。
标签: next.js http-status-code-404 server-side-rendering dynamic-routing getserversideprops