Next.js 序列化从“getServerSideProps”返回的“.res”时出错

Fyl*_*Fyl 8 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,
    },
  };
}
Run Code Online (Sandbox Code Playgroud)
import Binance from "node-binance-api"

const binance = new Binance().options({
  APIKEY: 'xxx',
  APISECRET: 'xxx'
});

export default binance;
Run Code Online (Sandbox Code Playgroud)

错误输出:

Error: Error serializing `.res` returned from `getServerSideProps` in "/dashboard".
Reason: `undefined` cannot be serialized as JSON. Please use `null` or omit this value.
Run Code Online (Sandbox Code Playgroud)

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

谢谢你!

Dia*_*aBo 20

这是我在 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
    },
  };
}
Run Code Online (Sandbox Code Playgroud)


小智 1

当您通过 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
  }
}
Run Code Online (Sandbox Code Playgroud)

您可以在此链接上阅读更多详细信息,https://nextjs.org/docs/basic-features/data-fetching#getserversideprops-server-side-rendering