繁体   English   中英

如何解决 Next.js 中 getServerSideProps 的“序列化”错误

[英]How can I resolve the error of 'serializing' from getServerSideProps in Next.js

我刚刚将服务器从const server = "https://backend.yourguide.pk"更改为const server = "https://stage.yourguide.pk" ,现在显示此错误。 如何解决?

getServerSideProps 的代码:

export async function getServerSideProps(context) {
  let experience = [];
  const server = 'stage.yourguide.pk';
  try {
    const data = await fetch(
      `${server}/api/user/getallexperience?title=${context.params.experiencesTitle}`,
      {
        method: 'GET',
        headers: { 'Content-Type': 'application/json' },
      }
    );
    experience = await data.json();
  } catch (error) {
    console.log('error is ', error);
  }

  return {
    props: {
      title: context.params.experiencesTitle,
      experience: experience.results,
    },
  };
}

错误 - SerializableError:序列化从“/”中的getServerSideProps返回的.experiences时出错。 原因: undefined不能序列化为JSON,请使用null或省略该值。

在此处输入图像描述

出于某种原因, experience被设置为undefined ,而undefined不是有效的 JSON 值。 这可以在检查的帮助下解决,如下所示:

export async function getServerSideProps(context) {
  let experience;
  const server = "stage.yourguide.pk";
  try {
    const data = await fetch(
      `${server}/api/user/getallexperience?title=${context.params?.experiencesTitle}`,
      {
        method: "GET",
        headers: { "Content-Type": "application/json" },
      }
    );
    experience = await data.json();
  } catch (error) {
    console.log("error is ", error);
  }

  return {
    props: {
      title: context.params?.experiencesTitle || null,
      experience: experience?.results || null,
    },
  };
}

现在,为什么你变得undefined 好吧,这可能是因为您没有使用正确的端点或路径,或者没有提供正确的参数等。此外,您的错误是说.experiences而您有.experience

确保您没有打错字。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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