16

目前我正在关注如何在 getInitialProps 中重定向用户的示例

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

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

context.res.writeHead(404)
context.res.end();

请注意,我知道使用 ExpressJs 和使用 statuscode 404 是可行的,但是,对于这个项目,我不允许使用 ExpressJs,所以我需要使用典型的 nodejs writeHead 来做到这一点。

4

7 回答 7

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} />
     */
  }
}

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

于 2017-12-14T17:34:14.067 回答
18

Next v10 允许返回 404 页面(不是使用道具,而是如下所示)

  if (!checkItem) {
    return {
      notFound: true
    }
  }

适合我的完整代码:✅✅✅</p>

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']),
    }
  }
})

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

于 2021-04-28T12:04:12.860 回答
6

按照以下方式实现您的 getInitialProps:

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

        ...

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

            return {
                err: {
                    statusCode: 404
                },
            };
        }
        ...

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

于 2019-01-16T09:20:15.130 回答
3

从 NextJS 10 开始,您现在可以notFound: true在返回对象中包含getStaticProps && getServerSideProps重定向到 404 页面

以下是发行说明:https ://nextjs.org/blog/next-10#redirect-and-notfound-support-for-getstaticprops--getserversideprops

于 2021-01-14T09:59:03.477 回答
1
import App, { Container } from 'next/app'
import React from 'react'
import Head from 'next/head'
import * as Sentry from '@sentry/node'
import Error from './_error'

require('es6-promise').polyfill()
require('isomorphic-fetch')

class MyApp extends App {
  static async getInitialProps({ Component, ctx }) {
    let pageProps = {}
    let e
    if (Component.getInitialProps) {
      try {
        pageProps = await Component.getInitialProps(ctx)
      } catch (error) {
        e = error
        Sentry.captureException(error) //report to sentry
      }
    }
    return { pageProps, e }
  }

  render() {
    const { Component, pageProps, e } = this.props
    if (e) {
      return <Error /> // customize your error page
    }
    return (
      <Container>
        <Head>
          <title> Your title</title>
        </Head>
        <Component {...pageProps} />
      </Container>
    )
  }
}

export default MyApp

这就像一个魅力〜只需尝试在下一个/应用程序中捕获,然后它适用于所有页面

于 2019-01-25T07:01:16.737 回答
1

如果您只需要像在cra中那样实现404 PAGE

提供的代码可能会有所帮助:例如。

 import AComponent from '../acomponent';
 import Error from '../error';
  
 const User = (data) => {

   return data.id ? <AComponent /> : <Error />
 }

 User.getInitialProps = async (ctx) => {
   const res = await fetch(...data) // list of items = []
   const data = await res.json()

   return data;
 }
于 2020-10-01T07:47:03.223 回答
0

我正在使用它,它对我有用

res.sendStatus(404)
于 2022-01-26T10:17:10.273 回答