Next.js 错误序列化从 `getServerSideProps` 返回的 `.res`

时间:2021-03-26 13:21:59

标签: javascript reactjs next.js

当我使用 getServerSideProps 函数从 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;

错误输出:

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

我不确定如何解决此错误。我只是希望能够通过将响应作为道具发送到另一个组件中来挖掘(并显示)响应。

谢谢!

1 个答案:

答案 0 :(得分:0)

通过 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