如何处理调用 API 的 Next.js 中动态路由的未找到 404? [英] How to handle not found 404 for dynamic routes in Next.js which is calling API?

查看:39
本文介绍了如何处理调用 API 的 Next.js 中动态路由的未找到 404?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a website which is developed by React and Next.js in client side and calls APIs from Asp.Net core server to fetch dynamic data such as products and categories.

问题是当我在请求的 URL 中有未定义的参数需要传递给 API 以获取相关数据时,如何重定向到 404 not found 页面.

The issue is how to redirect to 404 not found page when I have undefined parameters in requested URL which needed to pass to API to get related data.

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

For example, if the requested URL is https://domain/product/unique-title-of-product, "unique-title-of-product" will pass to API and responded data will show in product details page. But if the requested URL is "https://domain/product/not-existed-title", how do I check this and redirect it to 404-not-found-page?

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

I don't want to pass undefined-title to server because it will respond null or 200 or 500 internal server error if it is not handled. Then it seems I have to handle 404 redirect in client side without any server side interaction. But when I try to redirect with 404 status code in next.js, the status code will not to be reflected in browser.

在客户端处理此问题的最佳解决方案是什么?还是我应该在服务器端处理它?<​​/p>

What is the best solution to handle this issue in client side? Or should I handle it server side?

推荐答案

可以放validation,检查param是否有效,并进行相应的重定向

You can put validation, check if param is valid or not, and redirect accordingly

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

nextjs take care of pages/404.js, you do not need to explicitly add it unless you want to customize it.

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

Consider the following page 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

这篇关于如何处理调用 API 的 Next.js 中动态路由的未找到 404?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆