[英]Next.js Error Serializing `results` returned from `getServerSideProps`
[英]Next.js Error serializing `.res` returned from `getServerSideProps`
當我使用 getServerSideProps function 從 Binance API 檢索數據時,出現以下錯誤。
import binance from "../config/binance-config";
export async function getServerSideProps() {
const res = await binance.balance((error, balances) => {
console.info("BTC balance: ", balances.BTC.available);
});
return {
props: {
res,
},
};
}
import Binance from "node-binance-api"
const binance = new Binance().options({
APIKEY: 'xxx',
APISECRET: 'xxx'
});
export default binance;
錯誤 output:
Error: Error serializing `.res` returned from `getServerSideProps` in "/dashboard".
Reason: `undefined` cannot be serialized as JSON. Please use `null` or omit this value.
我不確定如何解決此錯誤。 我只是希望能夠通過將響應作為道具發送到另一個組件中來挖掘(和顯示)響應。
謝謝!
這是我在 NextJs 中解決它的方法
// Get Data from Database
export async function getServerSideProps(ctx) {
const { params } = ctx;
const { slug } = params;
await dbConnect.connect();
const member = await Member.findOne({ slug }).lean();
await dbConnect.disconnect();
return {
props: {
member: JSON.parse(JSON.stringify(member)), // <== here is a solution
},
};
}
當您通過 Api 獲取數據時,將數據轉換為 json 格式,
export async function getServerSideProps(context) {
const res = await fetch(`https://.../data`)
const data = await res.json()
if (!data) {
return {
redirect: {
destination: '/',
permanent: false,
},
}
}`enter code here`
return {
props: {}, // will be passed to the page component as props
}
}
您可以在此鏈接上閱讀更多詳細信息, https://nextjs.org/docs/basic-features/data-fetching#getserversideprops-server-side-rendering
將 API 中的 res 放在花括號中
const { res } = await binance.balance((error, balances) => {
console.info("BTC balance: ", balances.BTC.available);
});
return {
props: {
res,
},
};
這實際上是一個簡單的錯誤。 從getServerSideProps
返回的props
必須用大括號括起來,如下所示:
return {props: {res}}
如果響應中沒有返回空值,這將清除序列化錯誤
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.