为什么我在自定义的 Next.js 404.js 页面中没有收到 404 响应代码?

huangapple go评论58阅读模式
英文:

Why do I not get 404 response code for custom Next.js 404.js page?

问题

以下是已翻译的内容:

这里有两种情况。一种有效,另一种无效。

我已经在Next.js 12的pages目录中添加了一个404.js页面。

如果我访问一个没有定义路由的URL,例如domain.tld/non-existing-route,那么我会收到404 HTTP状态码,并显示我的自定义未找到页面。

然而,如果我访问具有参数的路由,例如domain.tld/post/slug并提供一个不存在的slug,我仍然会收到自定义的404页面,但这次HTTP状态码是200。

在我的post/[slug].js页面中,这是我的getServerSideProps

const getServerSideProps = async (context) => {

    const { slug } = context.params || {}

    var url = `/post/data?slug=${slug}`

    const data = await apiClient(url)

    return {
        props: {
            ...data,
        }
    }
}

当slug不存在时,我们的API会返回404和这个JSON:

{
  "type": 404,
  "message": "Not found"
}

这将由我们的apiClient代码处理,并将此JSON返回给getServerSideProps

{ 
   statusCode: 404, 
   message: 'Item does not exist' 
}

然后在我们的/post/[slug].js文件中,我们有以下JSX:

import NotFound from '../../404';

const Post = ({
    post,
    seoParameters,
    statusCode,
}) => {
    return <>
       {
           statusCode === 404
             ?
                <NotFound />
             :
                <Layout />
       }
    </>;
}

可能出了什么问题?

英文:

Here's two scenarios. One works, the other does not.

I have added a 404.js page to my pages directory in Next.js 12.

If I go to a URL for which there is no route defined, for example domain.tld/non-existing-route then I get 404 HTTP Status Code and my custom not found page would be shown.

However, if I go to a route that has parameters, for example domain.tld/post/slug and provide a slug that does not exist, I still get my custom 404 page, but this time with HTTP Status Code 200.

In my post/[slug].js page, this is my getServerSideProps:

const getServerSideProps = async (context) =&gt; {

    const { slug } = context.params || {}

    var url = `/post/data?slug=${slug}`

    const data = await apiClient(url)

    return {
        props: {
            ...data,
        }
    }
}

When the slug does not exist, our API returns 404 and this JSON:

{
  &quot;type&quot;: 404,
  &quot;message&quot;: &quot;Not found&quot;
}

Which would be handled by our apiClient code and this JSON would be returned to getServerSideProps:

{ 
   statusCode: 404, 
   message: &#39;Item does not exist&#39; 
}

Then in our /post/[slug].js file we have this JSX:

import NotFound from &#39;../../404&#39;

const Post = ({
    post,
    seoParameters,
    statusCode,
}) =&gt; {
    return &lt;&gt;
       {
           statusCode === 404
             ?
                &lt;NotFound /&gt;
             :
                &lt;Layout /&gt;
       }
    &lt;/&gt;
}

What could be wrong?

答案1

得分: 1

在Next.js页面目录中,在getServerSideProps函数中返回notFound以告诉Next.js这不是一个有效的路由。

export getServerSideProps = async (context) => {
  const data = await yourApiClient(`/post/data?slug=${slug}`);

  if (!data) { // 确保data是你的API的正确键
    return { notFound: true };
  }
 
  return { props: { data } };
}

页面不需要发送额外的props,因此您可以删除状态码检查,只需在页面上返回Layout

const Post = (props) => {
   console.log(props);
   return <Layout />;
}

export default Post;
英文:

In the Next.js pages directory, return notFound in the getServerSideProps function to tell Next.js it's not a valid route.

export getServerSideProps = async (context) =&gt; {
  const data = await yourApiClient(`/post/data?slug=${slug}`);

  if (!data) { // make sure data is the proper key for your api
    return { notFound: true };
  }
 
  return { props: { data } };
}

No additional props need to be sent to the page so you can remove the status code check and only return the Layout on the page.

const Post = (props) =&gt; {
   console.log(props);
   return &lt;Layout /&gt;;
}

export default Post;

huangapple
  • 本文由 发表于 2023年5月22日 23:45:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76307883.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定