next.js 404:页面找不到页面找不到404

f45qwnt8  于 2022-11-05  发布在  其他
关注(0)|答案(1)|浏览(241)

我有一个显示产品详细信息的动态页面,如果未找到请求的产品,外部服务器将返回404,问题是getServerSideProps显示空白页面,而不是重定向到404
下面是代码:

// pages/[slug].tsx

export const getServerSideProps: GetServerSideProps = async ({
  params,
  res,
}) => {
  const { product, relatedProducts } = await getProductDetail(
    params?.slug as string
  );

  if (res.statusCode === 404) {
    return {
      redirect: { destination: "/404", permanent: false },
    };
  }

  return {
    props: {
      product,
      relatedProducts,
    },
  };
};

我还尝试使用notFound属性

if (res.statusCode === 404) {
    return {
      notFound: true
    };
  }

这是我第一次遇到这个问题,因为服务器重定向在其他(静态)页面中工作得很好
非常感谢您的帮助

cyej8jka

cyej8jka1#

从NextJS 10开始,你不必显式返回你的404页面,这要归功于新的标志notFound:您可以在getStaticProps和getServerSideProps中使用它来自动触发默认的404页面或您自己的自定义404页面。

// pages/[slug].tsx

export const getServerSideProps: GetServerSideProps = async ({
  params,
  res,
}) => {
  const { product, relatedProducts } = await getProductDetail(
    params?.slug as string
  );

  const data = await res.json()

  if (!data) {
    return {
      notFound: true,
    }
  }
  // if (res.statusCode === 404) {
    // return {
      // redirect: { destination: "/404", permanent: false },
    // };
  // }

  return {
    props: {
      product,
      relatedProducts,
    },
  };
};

文档参考

  • 在Nextjs10上未找到支持
  • 在getStaticProps上找不到
  • 在获取服务器版本属性时未找到
  • 自定义404页面

相关问题