首页 > 解决方案 > getStaticProps 的 "notFound" 属性对页面 http 状态码没有影响

问题描述

我刚刚安装了一个新的 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。

标签: javascriptnext.jsstatic-site-generation

解决方案


对于这个特定的用例,您必须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 生成 - 类似于在服务器端呈现期间发生的情况。这意味着如果notFound: true从您那里返回,您将获得页面请求getStaticProps的正确状态代码。404


推荐阅读