亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何處理調用 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 關注
  • 495 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號