为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕沐林林 2023-10-14 16:53:18
我有一个由 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 状态代码进行重定向时,状态代码将不会反映在浏览器中。在客户端处理此问题的最佳解决方案是什么?或者我应该在服务器端处理它?
查看完整描述

3 回答

?
MMMHUHU

TA贡献1834条经验 获得超8个赞

获得 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

    }

  };

};


查看完整回答
反对 回复 2023-10-14
?
扬帆大鱼

TA贡献1799条经验 获得超9个赞

您可以进行验证,检查参数是否有效,并相应地重定向


nextjs 负责pages/404.js,除非您想自定义它,否则不需要显式添加它。


考虑以下页面pages/post/[pid].js:


import { useRouter } from 'next/router'


const Post = () => {

  const router = useRouter()

  const { pid } = router.query

  // if id is not valid, explicitly redirect to 404 page

   if(!pid){

       router.push('/404')

   }

  return <p>Post: {pid}</p>

}


export default Post


查看完整回答
反对 回复 2023-10-14
?
浮云间

TA贡献1829条经验 获得超4个赞

App Router 的方法是调用notFound()函数:


import { notFound } from 'next/navigation'

 

async function fetchUser(id) {

  const res = await fetch('https://...')

  if (!res.ok) return undefined

  return res.json()

}

 

export default async function Profile({ params }) {

  const user = await fetchUser(params.id)

 

  if (!user) {

    notFound()

  }

 

  // ...

}

查看完整回答
反对 回复 2023-10-14
  • 3 回答
  • 0 关注
  • 170 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信