如何处理调用 API 的 Next.js 中动态路由的未找到 404?

Meh*_*hdi 10 javascript reactjs asp.net-core next.js

我有一个由 React 和 Next.js 在客户端开发的网站,并从 Asp.Net core 服务器调用 API 来获取动态数据,例如产品和类别。

问题是当我请求的 URL 中有未定义的参数(需要传递给 API 来获取相关数据)时,如何重定向到 404 未找到页面。

例如,如果请求的 URL 是 https://domain/product/unique-title-of-product,则“unique-title-of-product”将传递给 API,响应的数据将显示在产品详细信息页面中。但是,如果请求的 URL 是“https://domain/product/not-existed-title”,我该如何检查并将其重定向到 404-not-found-page?

我不想将 undefined-title 传递给服务器,因为如果不处理它,它将响应 null 或 200 或 500 内部服务器错误。那么看来我必须在客户端处理 404 重定向,而无需任何服务器端交互。但是当我尝试在 next.js 中使用 404 状态代码进行重定向时,状态代码将不会反映在浏览器中。

在客户端处理此问题的最佳解决方案是什么?或者我应该在服务器端处理它?

Vin*_*t J 13

获得 GoogleBot 理解的真实“HTTP 404”响应的一种方法是生成 404 服务器端。

首先,在 /pages/404.js 中编写默认的 404.js 页面。

之后,将此功能添加到您的动态页面中:

export async function getServerSideProps (context) {
  // this will be called server-side only
  const pid = context.params.pid;

  // connect to your db to check if it exists, make a webservice call...
  if (!checkIfExists(pid)) {
    return { notFound: true };
    // this will display your /pages/404.js error page,
    // in the current page, with the 404 http status code.
  }
  return {
    props: {
      pid,
      // you may also add here the webservice content
      // to generate your page and avoid a client-side webservice call
    }
  };
};
Run Code Online (Sandbox Code Playgroud)

  • @Rajesh Koothropali -> 因为这个问题有一个矛盾。404 HTTP 错误 *是* 服务器端错误;在客户端,你永远无法得到真正的“404”,充其量,你可以手动模仿错误页面或消息。如果您想获得 404 的好处,例如正确的搜索引擎索引,那么您必须在服务器端进行。 (2认同)