简体   繁体   中英

getServerSideProps functions response cannot be serialized as JSON in Next.js

I am building a Next.js application with multiple pages with dynamic routing. Each page has multiple axios calls to the backend that are called with useEffect. My goal is to instead call these functions with getServerSideProps functions for speed purposes as the application is scaled to accomodate a larger user database.

My issue is when i try to recieve emails from the database, I get the error:

Error: Error serializing.allEmails.config.transformRequest[0] returned from getServerSideProps in "/emails". Reason: function cannot be serialized as JSON. Please only return JSON serializable data types.

I want to recieve emails and pass it into props where i can then access the data on the page.

 import React, { useState, useEffect, useContext } from 'react'; import axios from 'axios'; import jsHttpCookie from 'cookie'; import jsCookie from 'js-cookie'; const Emails = ({allEmails}) => { const [emails, setEmails] = useState(allEmails); return ( <></> ) } export async function getServerSideProps({req, res}) { const {token} = jsHttpCookie.parse(req.headers.cookie); const allEmails = await axios.get("http://localhost:8000/api/allCompanyEmails"); console.log(allEmails, "all data") return { props: { allEmails } } } export default Emails;

allEmails is actually AxiosResponse type , it is not the data you get from api. And it contains non-serializable stuff like functions and etc.

To get the data you need to access data property of this response:

export async function getServerSideProps({req, res}) {
    const {token} = jsHttpCookie.parse(req.headers.cookie);
    const response = await axios.get("http://localhost:8000/api/allCompanyEmails");
    console.log(response, "all data")
  
    return {
        props: {
          allEmails: response.data
        }
    }
  }

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