reactjs - 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 };
}
}
我认为这是一种更清洁、更好的语法
推荐阅读
- php - 修改 get_avatar() 函数
- r - Problem with Analysing Turkish Text while using stopwords "tr" with R
- c# - 在 C# 中禁用 Excel 工作簿的自动保存?
- http - 如何从 json 请求创建一个复杂的类
- amazon-web-services - 在 AWS Lambda 中访问用户身份
- python - 在 matplotlib 中,使用 plot 和 hist 的返回绘制直方图
- python - 如何根据时间(以毫秒为单位)对 JSON 列表进行排序?
- symfony - 带有过滤器列表的 symfony easyadmin 表单字段类型实体
- css - 设置元素之间的空间 - 边距顶部/底部
- c# - 将浮点数保存到文本文件无法正常工作