【问题标题】:Next.js return the 404 error page in getInitialPropsNext.js 在 getInitialProps 中返回 404 错误页面
【发布时间】:2018-05-15 03:39:43
【问题描述】:

目前我正在关注如何在 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 来完成。

【问题讨论】:

  • Next.js 10 让这个变得超级简单,在下面找到最新的答案

标签: javascript node.js serverside-javascript next.js nextjs


【解决方案1】:

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

你可以这样做:

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

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

【讨论】:

    【解决方案2】:

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

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

    适合我的完整代码:✅✅✅

    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 年公认的答案。(Next.js v10.2)
    • @Vadorequest 否,OP 要求 getInitialProps,但未找到仅适用于 getStaticPropsgetServerSideProps 的支持
    • wrapper 来自哪里?
    • @Newbyte 它来自: import { HYDRATE, createWrapper } from 'next-redux-wrapper' export const wrapper = createWrapper(initStore)
    【解决方案3】:

    按照以下方式实现您的 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 传递。

    【讨论】:

      【解决方案4】:

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

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

      【讨论】:

        【解决方案5】:
        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
        
        

        这就像一个魅力〜 只需在 next/app 中尝试 catch,然后它适用于所有页面

        【讨论】:

          【解决方案6】:

          如果您只需要像在 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;
           }
          

          【讨论】:

            【解决方案7】:

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

            res.sendStatus(404)
            

            【讨论】:

              猜你喜欢
              • 2021-03-14
              • 2018-04-03
              • 1970-01-01
              • 2021-09-28
              • 1970-01-01
              • 2018-04-03
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多