【发布时间】:2021-09-10 06:31:29
【问题描述】:
在我的一条路线中使用getStaticProps 和getStaticPaths 方法时,我尝试运行next build,但每次都失败。首先,它只是无法连接到我的 API(很明显,它们是使用 Next.js 的 API 路由创建的,这些路由在不运行 Next.js 应用程序时不可用)。我认为也许在后台运行开发服务器会有所帮助。确实如此,但产生了另一个问题,例如:
Error: Cannot find module for page: /reader/[id]
Error: Cannot find module for page: /
> Build error occurred
Error: Export encountered errors on following paths:
/
/reader/1
不知道为什么。这是/reader/[id]的代码:
const Reader = ({ reader }) => {
const router = useRouter();
return (
<Layout>
<pre>{JSON.stringify(reader, null, 2)}</pre>
</Layout>
);
};
export async function getStaticPaths() {
const response = await fetch("http://localhost:3000/api/readers");
const result: IReader[] = await response.json();
const paths = result.map((result) => ({
params: { id: result.id.toString() },
}));
return {
paths,
fallback: false,
};
}
export async function getStaticProps({ params }) {
const res = await fetch("http://localhost:3000/api/readers/" + params.id);
const result = await res.json();
return { props: { reader: result } };
}
export default Reader;
没什么特别的。我从文档中重写并适应了我的网站的代码。
这是/api/readers/[id] 处理程序。
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
const knex = getKnex();
const { id } = req.query;
switch (req.method) {
case "GET":
try {
const reader = await knex
.select("*")
.from("readers")
.where("id", id)
.first();
res.status(200).json(reader);
} catch {
res.status(500).end();
}
break;
}
}
也没什么特别的。那么为什么每次我尝试构建我的应用程序时它都会崩溃?感谢您提前提供任何帮助。
【问题讨论】: