【问题标题】:NextJS: 404 page when Express endpoint returns 404?NextJS:Express 端点返回 404 时的 404 页面?
【发布时间】:2019-11-14 12:36:52
【问题描述】:

API 端点 (Express) 发送 404。
return res.status(404).json({ message: 'Not Found !!!' })

_app 组件中

static async getInitialProps({ Component, ctx }) {
    try {
      const pageProps = Component.getInitialProps
        ? await Component.getInitialProps(ctx)
        : {}

      const statusCode = ctx.res && ctx.res.statusCode

      return {
        pageProps,
        statusCode
      }
     } catch (err) {
       // What to do here?
     }

应用组件在另一个组件中调用getInitialProps...这里调用了返回404状态的API。

static async getInitialProps(ctx) {
   try {
      const response = await axios.get(route.API_POST(id))
      // do something with response
    } catch (err) {
      //???????
    }
}

只有,它没有。它返回200

当 Express 端点返回 404 状态时,如何在 NextJS 中呈现 404 页面?

【问题讨论】:

    标签: next.js


    【解决方案1】:

    在你正在做的自定义服务器中:

    app.render(req, res, page, params)
    

    如果你在 express 中修改 res 对象,将 statusCode 更改为 404,在 NextJS 的路由组件中,你将拥有 res 对象和 statusCode 属性。如果res.statusCode 永远不是 404,请尝试在 getInitialProps 中覆盖它

    static async getInitialProps({ Component, ctx }) {
        try {
          const pageProps = Component.getInitialProps
            ? await Component.getInitialProps(ctx)
            : {}
    
          const statusCode = ctx.res && ctx.res.statusCode
    
         ctx.res.statusCode = 404
    
          return {
            pageProps,
            statusCode
          }
         } catch (err) {
           // What to do here?
           // Here you cannot do anything because 
           // you don’t have any throw in the previous statements
         }
    }
    

    我注意到上面的代码是关于_app.jsgetInitialProps,我不知道这是否适用于这个组件。但是,尝试添加路线并执行以下操作:

    static getInitialProps({ res }) {
      if (res) {
        res.statusCode = 404
      }
    
      return {}
    }
    

    【讨论】:

      猜你喜欢
      • 2020-05-12
      • 2013-08-28
      • 1970-01-01
      • 1970-01-01
      • 2011-11-22
      • 2020-12-23
      • 1970-01-01
      • 1970-01-01
      • 2019-02-28
      相关资源
      最近更新 更多