Next.js 在 getInitialProps 中返回 404 错误页面

Tho*_*rth 14 javascript serverside-javascript node.js next.js nextjs

目前我正在关注这个关于如何在 getInitialProps 中重定向用户的例子

https://github.com/zeit/next.js/wiki/Redirecting-in-%60getInitialProps%60

问题是,如果我想像这样返回 404,它将返回一个空白页面,而不是通常的 Next.js 404 错误页面。

context.res.writeHead(404)
context.res.end();
Run Code Online (Sandbox Code Playgroud)

请注意,我知道使用 ExpressJs 和使用状态码 404 可以工作,但是,对于这个项目,我不允许使用 ExpressJs,因此我需要使用典型的 nodejs writeHead 来执行此操作。

Ber*_*ron 20

为此,您必须在页面中呈现错误页面。

你可以这样做:

import React from 'react'
import ErrorPage from 'next/error'

class HomePage extends React.Component {
  static async getInitialProps(context) {
    try {
      const data = await retrieveSomeData()
      return { data }
    } catch (err) {
      // Assuming that `err` has a `status` property with the HTTP status code.
      if (context.res) {
        context.res.writeHead(err.status)
      }
      return { err: { statusCode: err.status } }
    }
  }

  render() {
    const { err, data } = this.props

    if (err) {
      return <ErrorPage statusCode={err.statusCode} />
    }

    /*
     * return <Something data={data} />
     */
  }
}
Run Code Online (Sandbox Code Playgroud)

如果您有自定义错误页面,则不必导入next/error,而是必须导入自定义_error页面。


Ale*_*pov 9

Next v10 允许返回 404 页面(不带道具,但就像下面一样简单)

  if (!checkItem) {
    return {
      notFound: true
    }
  }
Run Code Online (Sandbox Code Playgroud)

对我有用的完整代码:???

export const getServerSideProps = wrapper.getServerSideProps(async ({ req, res, locale, query, store }) => {
  const { productId, categoryId } = query
   
  const checkItem = await getProductBySlugSSR(productId, categoryId, store)

  if (!checkItem) {
    return { // <-----------------does the trick here!!
      notFound: true
    }
  }
    
  return {
    props: {
      ...await serverSideTranslations(locale, ['common']),
    }
  }
})
Run Code Online (Sandbox Code Playgroud)

文档:https : //nextjs.org/blog/next-10#notfound-support

  • @Vadorequest 否,OP 要求“getInitialProps”,但未找到支持仅适用于“getStaticProps”和“getServerSideProps” (4认同)

小智 7

按照以下方式实现 getInitialProps:

    static async getInitialProps(context) {
        const {res} = context;

        ...

        if ([something went wrong]) {
            if (res) {
                res.statusCode = 404;
            }

            return {
                err: {
                    statusCode: 404
                },
            };
        }
        ...
Run Code Online (Sandbox Code Playgroud)

然后在 render() 中检查是否err在状态中定义,在这种情况下返回 ErrorPage (默认或自定义,取决于您的实现),就是这样!err 中的 statusCode 只是为了在 ErrorPage 上提供更精细的消息,因此需要将其作为 props 传递。


sur*_*egi 5

我是这样做的

import ErrorPage from 'next/error'

const Mycomponenet = () =>{
   if (!exists) {
        return <ErrorPage statusCode={404}/>
      }
}

Run Code Online (Sandbox Code Playgroud)