簡體   English   中英

如果getStaticProps中的數據無效,如何重定向到404頁面?

[英]How to redirect to 404 page if data is invalid in getStaticProps?

在我的 Next.js 應用程序中,我將獲取作者的所有文章。 我從請求參數中獲取作者 ID。 我使用getStaticPaths預先生成了我的一些作者。

getStaticPaths我將fallback設置為true 如果正確提供了作者 ID,它可以正常工作,但是如果您寫了錯誤的文本來請求參數,它會返回一個錯誤。

[authorId].js頁面

export async function getStaticPaths() {
  const fetchAuthors = await axios.get(
    "http://localhost:3000/api/articles/authors"
  );

  return {
    paths: [
      ...fetchAuthors.data.map((item) => {
        return { params: { authorId: item.author._id } };
      }),
    ],
    fallback: true,
  };
}
export async function getStaticProps(context) {
  const {
    params: { authorId },
  } = context;

  const fetchArticles = await axios.get(
    `http://localhost:3000/api/articles/${authorId}/1`
  );

  const fetchAuthor = await axios.get(
    `http://localhost:3000/api/articles/authors/${authorId}`
  );

  return {
    props: {
      Articles: fetchArticles.data,
      Author: fetchAuthor.data,
    },
    revalidate: 60,
  };
}
const AuthorProfilePage = ({ Articles, Author }) => {
    return <>
             <div className={styles.authorImgContainerBig}>
             <Image
               src={Author.author.photo.url}
               className={styles.authorImgBig}
               layout="fill"
               objectFit="cover"
               quality={100}
               alt=""
              />
              </div>
           </>
}

如果作者 ID 存在於數據庫中,則它工作正常。 但是,如果您將例如“asljnsaf”作為作者 ID 傳遞,則會返回錯誤。

錯誤信息

Server Error
TypeError: Cannot read property 'author' of undefined

<Image
  55 |   src={
> 56 |     Author.author.photo.url ||
     |           ^
  57 |     "https://res.cloudinary.com/bizimsehir-gazetesi/image/upload/v1624802793/blank-profile-picture-973460_1280_duksmn.png"
  58 |   }
  59 |   className={styles.authorImgBig}

如果作者不存在,如何重定向到 404 頁面?

如果作者數據不存在,您可以直接從getStaticProps函數返回 404 頁面。

export async function getStaticProps(context) {
    const { params: { authorId } } = context;

    const fetchArticles = await axios.get(`http://localhost:3000/api/articles/${authorId}/1`);
    const fetchAuthor = await axios.get(`http://localhost:3000/api/articles/authors/${authorId}`);
    
    // Handle `undefined` author data
    if (!fetchAuthor.data) {
        return {
            notFound: true
        };
    }

    return {
        props: {
            Articles: fetchArticles.data,
            Author: fetchAuthor.data
        },
        revalidate: 60
    };
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM