Next JS [id] error Error serializing `.data` returned from `getServerSideProps` in "/services/[id]" 错误

Next JS [id] error Error serializing `.data` returned from `getServerSideProps` in "/services/[id]"

我制作了 Next JS 项目,我是这个程序中编码的新手,并且有一个“服务”文件夹。此文件夹中有 index.js 和 [id].js(详细信息页面)。所有数据均来自 Next API。 Index.js有效,没有问题。但是当我单击详细信息元素时,会看到错误。我不知道我的错误是什么

Error: Error serializing `.data` returned from `getServerSideProps` in "/services/[id]". Reason: `object` ("[object Promise]") cannot be serialized as JSON. Please only return JSON serializable data types.

index.js

      <section className="services-main">
        <div className="services-main-context container">
          <MainPageServices posts={posts} />
        </div>
      </section>

     ....

export async function getStaticProps() {
  const res = await fetch("http://localhost:3000/api/servicesApi/");
  const posts = await res.json();

  return {
    props: {
      posts,
    },
  };
}

MainPageServices 组件

     <div className="main-page-services-cards">
        {posts.map((card, key) => (
           <div key={card.id} className="service-card">
              <Link href={`/services/${card.id}`}>
                 <a>
                   <div className="card-img">
                      <Image src={card.img} alt="Services" />
                   </div>
                 </a>
              </Link>
           </div>
        ))}
      </div>

组件不工作(详细信息)

const ServiceDetails = ({ data }) => {
  
  console.log(data);
       return (
         <h1>{data.header}</h1>)  
       );
  };


export const getServerSideProps = async (context) => {
  const res = await fetch(`http://localhost:3000/api/servicesApi/${context.params.id}`);
  const data = res.json();

  return {
    props: {
      data,
    },
  };
};

我的详情页面API

import { servicesData } from "../../../data";

export default function handler(req, res) {
  const { id } = req.query;
  const service = servicesData.find((service) => service.id === parseInt(id));
  res.status(200).json(service);
}

我认为你需要等待 res.json() 因为你的错误表明你正在将一个承诺传递给你的道具。

const ServiceDetails = ({ data }) => {
  
  console.log(data);
       return (
         <h1>{data.header}</h1>)  
       );
  };


export const getServerSideProps = async (context) => {
  const res = await fetch(`http://localhost:3000/api/servicesApi/${context.params.id}`);
  const data = await res.json();

  return {
    props: {
      data,
    },
  };
};