简体   繁体   中英

Next.js Error serializing `.res` returned from `getServerSideProps`

I am getting the error below, when I use getServerSideProps function to retrieve data from 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 output:

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

I'm not sure how to resolve this error. I would just like to be able to mine (and display) the response by sending it as props in another component.

Thank you!

Here is how I solved it in 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
    },
  };
}

Convert your data into json format when you are fetching it through an Api,

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
  }
}

You can read more detail on this link, https://nextjs.org/docs/basic-features/data-fetching#getserversideprops-server-side-rendering

put res from API in Curly Brackets

    const { res } = await binance.balance((error, balances) => {
    console.info("BTC balance: ", balances.BTC.available);
  });

return {
    props: {
      res,
    },
  };

This is actually a simple error. The props that are being returned from getServerSideProps must be wrapped in curly brackets as shown below:

return {props: {res}}

This will clear the serialization error provided no nulls are being returned in response

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM