【发布时间】:2022-08-24 14:45:20
【问题描述】:
这是我下一个 js 项目的一部分。该网站在 localhost 上运行良好,但是当我将其部署在 vercel 上时,/blogs/book/chapter 页面显示找不到文件,请在此处输入图像描述 500 错误。
动态路由文件夹结构
章节.js
import fs from \"fs\";
import path from \"path\";
import Head from \"next/head\";
import DefaultErrorPage from \"next/error\";
import { useRouter } from \"next/router\";
import matter from \"gray-matter\";
import { marked } from \"marked\";
import styles from \"../../../../styles/blog/Chapter.module.css\";
import { capitalise } from \"../../../../components/blog/Capitalise\";
import BlogPostBottom from \"../../../../components/blog/BlogPostBottom\";
export default function Chapter({ book, chapter, frontmatter, content }) {
// Destructuring
const { description } = frontmatter;
// Router Variable
const router = useRouter();
// If fallback then show this
if (router.isFallback) {
// if (router.isFallback || !book || !chapter || !content) {
return <div>Loading...</div>;
}
if (!book || !chapter || !content || !frontmatter) {
return (
<div>
<DefaultErrorPage statusCode={404} />
</div>
);
}
return (
<div className={styles.bookChapter}>
<Head>
<title>{`${capitalise(chapter)} | ${capitalise(
book
)} | Blog | Manav Goyal`}</title>
<meta
name=\"description\"
content={`Read Blog about this book ${book} covering chapter ${chapter} of topics ${description}`}
/>
</Head>
<h1>{`${capitalise(chapter)} - ${capitalise(book)}`}</h1>
<section
className={styles.bookChapterContent}
dangerouslySetInnerHTML={{ __html: marked(content) }}
></section>
<BlogPostBottom slug={`/blog/${book}`} />
</div>
);
}
export async function getStaticPaths() {
return {
paths: [{ params: { book: \"css\", chapter: \"bootstrap\" } }],
// paths: [],
fallback: true,
};
}
// Web crawlers, won\'t be served a fallback and instead the path will behave as in fallback: \'blocking\'
// fallback: true is not supported when using `next export`
export async function getStaticProps({ params }) {
const { book, chapter } = params;
let chapterPost = null;
try {
chapterPost = await fs.promises.readFile(
path.join(`posts/${book}/${chapter}.md`),
\"utf-8\"
);
} catch (err) {}
const { data: frontmatter, content } = matter(chapterPost);
return {
props: {
book,
chapter,
frontmatter,
content,
},
// redirect: {
// destination: `/blog/${book}`,
// permanent: false,
// },
// revalidate: 1,
};
}
Chapter.defaultProps = {
book: \"css\",
chapter: \"bootstrap\",
frontmatter: { description: \"CSS\", id: \"1\" },
content: \"Error\",
};
帖子文件夹结构
错误
-
您可能应该使用
process.cwd来构造您要读取的文件路径,例如path.join(process.cwd(), `posts/${book}/${chapter}.md`)。见nextjs.org/docs/api-reference/data-fetching/…。
标签: next.js vercel dynamic-routing