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.

试着从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 };
}
}

我认为这是一个更干净,更好的语法

最新更新