【问题标题】:How to return a 404 Not Found page and HTTP status when an invalid parameter of a dynamic route is passed in Next.js?Next.js中传入动态路由的无效参数时,如何返回404 Not Found页面和HTTP状态?
【发布时间】:2021-08-18 18:27:01
【问题描述】:

例如,我有一个动态路由/blog/[article-id]

访问现有的博客文章/blog/id-that-exist 时,它按预期工作,现在我想妥善处理/blog/id-that-does-not-exist 的情况。

/blog/[id].jsx 中的代码类似于:

export const getStaticPaths async () => {
  return {
    fallback: true,
    paths: (await sequelize.models.Article.findAll()).map(
      article => {
        return {
          params: {
            pid: article.slug,
          }
        }
      }
    ),
  }
}

export const getStaticProps async () => {
  // Try to get it from the database. Returns none if does not exist.
  const article = await sequelize.models.Article.findOne({
    where: { slug: pid },
  });
  return { props: { article: article } };
}

const ArticlePage = (props) => {
  // This can happen due to fallback: true while waiting for
  // a page that was not rendered at build time to build.
  const router = useRouter()
  if (router.isFallback) {
    return <div>loading</div>;
  }
  return (
    <div>{props.article.body}</div>
  );
};

export const getStaticPaths = getStaticPathsArticle;
export const getStaticProps = getStaticPropsArticle;
export default ArticlePage;

我看到了这个相关的问题:How to handle not found 404 for dynamic routes in Next.js which is calling API?,但我不确定它是否和我在这里问的一样,因为这不依赖于正在使用的任何外部 API。

【问题讨论】:

    标签: next.js


    【解决方案1】:

    notFound: true 来自 Next.js 10

    从 Next.js 10 开始,我们可以这样做:

    export const getStaticProps async () => {
      // Try to get it from the database. Returns none if does not exist.
      const article = await sequelize.models.Article.findOne({
        where: { slug: pid },
      });
      if (!article) {
        return {
          notFound: true
        }
      }
      return { props: { article: article } };
    }
    

    如记录在:https://nextjs.org/docs/basic-features/data-fetching#getstaticprops-static-generation

    notFound 返回时,渲染函数 ArticlePage 永远不会被调用,而是返回默认的 404 页面。

    但请注意,ArticlePage 确实得到了

    由于某种原因处于开发模式:

    • 我没有收到预期的 404 HTTP 状态代码
    • ArticlePage,所以如果你忘记处理后备情况,它可能会由于缺少属性而崩溃

    这让我有点困惑。但在生产模式下,一切正常。

    Next.js 10 之前的解决方法

    https://github.com/vercel/next.js/discussions/10960#discussioncomment-1201 所示,您之前可以执行以下操作:

    const ArticlePage = (props) => {
      if (!props.article) {
        return <>
          <Head>
            <meta name="robots" content="noindex">
          </Head>
          <DefaultErrorPage statusCode={404} />
        </>
      }
      return (
        <div>{props.article.body}</div>
      );
    };
    

    但这并不理想,因为我相信它没有正确设置 HTTP 返回码,而且我不知道该怎么做。

    在 Next.js 10.2.2 上测试。

    【讨论】:

      猜你喜欢
      • 2015-01-07
      • 1970-01-01
      • 2015-01-09
      • 2018-10-23
      • 1970-01-01
      • 1970-01-01
      • 2016-07-11
      • 2016-07-01
      • 2020-09-04
      相关资源
      最近更新 更多