我有一个网站,它是由客户端的反应和Next.js开发的,并从Asp.Net核心服务器调用API来获取动态数据,如产品和类别。
问题是当我在请求的URL中有未定义的参数时,如何重定向到404找不到页面,这些参数需要传递到API以获取相关数据。
例如,如果请求的URL是https://domain/product/unique-title-of-product,则会将“产品的唯一标题”传递给API,并在产品详情页显示响应的数据。但是,如果请求的网址是"https://domain/product/not-existed-title",我如何检查并将其重定向到404not-found page?“
我不想将undefined-title传递给服务器,因为如果不处理它,它将返回null或200或500内部服务器错误。然后,似乎我必须在客户端处理404重定向,而不需要任何服务器端交互。但是当我尝试在next.js中使用404状态码重定向时,状态码不会在浏览器中反映出来。
在客户端处理这个问题的最佳解决方案是什么?或者我应该在服务器端处理它?
发布于 2020-12-06 21:56:44
您可以放入验证,检查param是否有效,并相应地重定向
nextjs负责pages/404.js,除非您想要自定义它,否则不需要显式添加它。
考虑以下页面/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发布于 2021-10-05 13:26:38
获得GoogleBot理解的真正“HTTP404”响应的一种方法是生成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
}
};
};https://stackoverflow.com/questions/65168343
复制相似问题