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

w46czmvw  于 12个月前  发布在  其他
关注(0)|答案(3)|浏览(128)

已关闭,此问题为opinion-based。它目前不接受回答。
**想改善这个问题吗?**更新问题,以便editing this post可以用事实和引用来回答。

8天前关闭
Improve this question
我有一个由React和Next.js在客户端开发的网站,并从Asp.NET核心服务器调用API来获取产品和类别等动态数据。
问题是如何重定向到404找不到页面时,我有未定义的参数,需要通过请求的URL的API获取相关数据。
例如,如果请求的URL是https://domain/product/unique-title-of-product,则“unique-title-of-product”将传递给API,响应的数据将显示在产品详细信息页面中。但是如果请求的URL是“https://domain/product/not-referenced-title”,我该如何检查并将其重定向到404-not-found-page?
我不想把未定义的标题传递给服务器,因为如果不处理它,它会响应null或200或500内部服务器错误。然后似乎我必须在客户端处理404重定向,而不需要任何服务器端交互。但是当我尝试在next.js中使用404状态代码重定向时,状态代码不会反映在浏览器中。
在客户端处理此问题的最佳解决方案是什么?还是应该在服务器端处理?

fykwrbwg

fykwrbwg1#

一种获得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
    }
  };
};
cgfeq70w

cgfeq70w2#

您可以放置验证,检查参数是否有效,并相应地重定向
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
eiee3dmh

eiee3dmh3#

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()
  }
 
  // ...
}

来源:https://nextjs.org/docs/app/api-reference/functions/not-found

相关问题