如何在 Next.js 中为 404 页面设置 404 状态代码

时间:2021-07-27 18:49:21

标签: javascript node.js http server next.js

如何在 Next.js 中为自定义 404 页面设置 404 状态代码?我是前端,熟悉后端,但根据此线程 https://github.com/vercel/next.js/discussions/10960 应该可以在 getStaticProps 中做,但问题是,也许我理解错误,但它允许执行诸如返回 notFound 或从 getStaticProps 重定向之类的操作,仅当在此函数中获取的数据是例如在这个例子中为空

export async function getStaticProps({ params: { id } }) {
  const res = await fetchContentfulPosts();
  const posts = await res
    .filter((r) => r.sys.id === id)
    .map((p) => {
      return {
        fields: p.fields,
        locale: p.sys.locale,
        tags: p.metadata.tags,
      };
    });

  const { locale, fields, tags } = posts[0];
  const { title, author, date, image, text, shareDesc } = fields;

  if (!posts) {
    return {
      redirect: {
        destination: '/404',
        statusCode: 301,
      },
    };
  }

  return {
    props: {
      title,
      author,
      date,
      text,
      image: image || null,
      locale,
      tags,
      shareDesc
    },
  };
}

仅当 Contentful 返回的数据为空时才会返回 404 状态,但如果有人输入不存在的 url 呢?然后我会得到状态码为 200 的 404。 我还尝试根据此文档 https://nextjs.org/docs/advanced-features/custom-error-page 修改错误页面,如下所示:

import { Layout, NotFoundComponent } from '../components';

function Error({ statusCode }) {
  return statusCode === 404 ? (
    <Layout title="404: This page could not be found" backgroundVideo noIndex>
      <NotFoundComponent />
    </Layout>
  ) : (
    <p>
      {statusCode
        ? `An error ${statusCode} occurred on server`
        : 'An error occurred on client'}
    </p>
  );
}

Error.getInitialProps = ({ res, err }) => {
  const statusCode = res ? res.statusCode : err ? err.statusCode : 404;
  return { statusCode };
};

export default Error;

但是好像只能从服务器获取状态码并允许显示,而不能设置到服务器。我希望所有 404 次点击都与响应代码 404 一起返回,这样就不会被编入索引。

非常感谢!

0 个答案:

没有答案