3 回答

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
}
};
};

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

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()
? }
?
? // ...
}
添加回答
舉報