【问题标题】:How to redirect user to notFound Page in getServerSideProps whenever an invalid params.id is entered in Next.JS每当在 Next.JS 中输入无效的 params.id 时,如何将用户重定向到 getServerSideProps 中的 notFound 页面
【发布时间】:2022-02-07 20:27:43
【问题描述】:
export const getServerSideProps = async ({ params }) => {
  const res = await fetch(
    `https://pixabay.com/api/?key=${process.env.API_KEY}&id=${params.id}`
  );

  const { hits } = await res.json();

  if (!hits) {
    return {
      notFound: true,
    };
  }

  return {
    props: { pic: hits[0] },
    notFound: true,
  };
};

每当用户输入无效的 params.id=====>

时,我都会不断收到此错误

服务器错误 FetchError:https://pixabay.com/api/?key=*************************************&id=**xzk** 处的无效 json 响应正文:JSON 中位置 1 处的意外令牌 E

我使用“xzk”作为无效的 id 值,而不是将用户重定向到 notFoundPage,它一直显示此错误,并且该错误甚至显示了我的 api-keys。请问我做错了什么?想法也很受欢迎。提前致谢。

【问题讨论】:

    标签: javascript node.js reactjs react-native next.js


    【解决方案1】:

    我找到了解决方案,即检查响应是否正常。如果它不是 Ok 那么它应该将用户重定向到在 if 语句中设置为 true 的 notFound 页面。

    export const getServerSideProps = async ({ params }) => {
      const { id } = params;
    
      const res = await fetch(
        `https://pixabay.com/api/?key=${process.env.API_KEY}&id=${id}`
      );
    
      if (!res.ok) {
        return {
          notFound: true,
        };
      }
    
      const { hits } = await res.json();
    
      return {
        props: { pic: hits[0] },
      };
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-08-20
      • 2021-04-16
      • 1970-01-01
      • 2020-10-17
      • 2021-08-31
      • 2021-10-17
      • 2021-05-03
      相关资源
      最近更新 更多