首页 > 解决方案 > getServerSideProps 返回布尔值时序列化错误

问题描述

当我使用 getServerSideProps 函数在道具时间轴内返回时,我收到以下错误,只是一个布尔值。

我不知道我做错了什么。

export async function getServerSideProps({ params }) {
  const id = params.id;
  const timeline = await verifyTimelineID(id);

  return {
    props: {
      timeline,
    },
  };
}

我的函数仅在存在具有发送 id 的事件并且返回 true 或 false 时才返回。

export async function verifyTimelineID(id) {
  axios
    .get(`${process.env.NEXT_PUBLIC_API_URL}/events/${id}`)
    .then(() => {
      return { exists: true };
    })
    .catch(() => {
      return { exists: false };
    });
}

错误输出:

Error: Error serializing `.timeline` returned from `getServerSideProps` in "/timeline/[id]".
Reason: `undefined` cannot be serialized as JSON. Please use `null` or omit this value.

标签: reactjsnext.js

解决方案


只需尝试从 verifyTimelineID 返回值并像这样编辑它。


export async function verifyTimelineID(id) {
  return axios
    .get(`${process.env.NEXT_PUBLIC_API_URL}/events/${id}`)
    .then(() => {
      return { exists: true };
    })
    .catch(() => {
      return { exists: false };
    });
}

另外我认为在这里使用 async await 会更好一些,如下所示。


export async function verifyTimelineID(id) {
    try {
        await axios.get(`${process.env.NEXT_PUBLIC_API_URL}/events/${id}`)
        return { exists: true };
    } catch(e) {
        return { exists: false };
    }
}

我认为这是一种更清洁、更好的语法


推荐阅读