【问题标题】:The "notFound" prop of getStaticProps has no effect on page http status codegetStaticProps 的 "notFound" 属性对页面 http 状态码没有影响
【发布时间】:2021-06-24 17:37:32
【问题描述】:

我刚刚安装了一个新的 Next.js 应用。它有以下页面:

// /pages/articles/[slug].js

import React from 'react'
import { useRouter } from 'next/router'
import ErrorPage from 'next/error'

const Article = (props) => {
  const router = useRouter()
  if (router.isFallback) {
    return <div>Loading..</div>
  }
  if (!props['data']) {
    return <ErrorPage statusCode={404} />
  }
  return (
    <div>
      Article content
    </div>
  )
}

export default Article

export const getStaticProps = async(context) => {
  const slug = context.params.slug
  const res = ["a", "b", "c"].includes(slug)
    ? {
      props: {
        data: slug
      }
    }
    : {
      props: {},
      notFound: true
    }
  return res
}

export const getStaticPaths = async () =>  {
  return {
    paths: [
      { params: { slug: "a" }},
      { params: { slug: "b" }},
      { params: { slug: "c" }}
    ],
    fallback: true
  }
}

当浏览器导航到一个不存在的页面(例如 http://localhost:3000/articles/d)时,它会按预期返回默认的 nextjs 404 页面。

但浏览器网络选项卡显示主文档的状态 200(404 错误页面)。网络选项卡中状态为 404 的唯一内容是 d.json 和 404.js。

我认为主文档也应该有 404 状态。 getStaticProps 文档谈到了返回值:

  • notFound - 一个可选的布尔值,允许页面返回 404 状态和页面

但在这种情况下,页面状态是 200 而不是 404。是否需要执行其他操作才能返回状态 404?

如果没有回退,状态为 404。

【问题讨论】:

    标签: javascript next.js static-site-generation


    【解决方案1】:

    对于这个特定用例,您必须改用fallback: 'blocking'

    export const getStaticPaths = async () =>  {
      return {
        paths: [
          { params: { slug: "a" }},
          { params: { slug: "b" }},
          { params: { slug: "c" }}
        ],
        fallback: 'blocking'
      }
    }
    

    fallback: true 不同,如果页面尚未生成,它将提供“后备”版本。我相信这就是您目前获得200 状态码的原因。

    相反,fallback: 'blocking' 将在呈现页面之前等待 HTML 生成 - 类似于在服务器端呈现期间发生的情况。这意味着如果从getStaticProps 返回notFound: true,您将获得页面请求的正确404 状态代码。

    【讨论】:

      猜你喜欢
      • 2019-07-15
      • 2019-10-24
      • 1970-01-01
      • 1970-01-01
      • 2011-11-25
      • 1970-01-01
      • 1970-01-01
      • 2019-11-26
      • 2019-10-25
      相关资源
      最近更新 更多