Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.3k views
in Technique[技术] by (71.8m points)

javascript - object` ("[object Response]") cannot be serialized as JSON?

I am trying to consume my api through code I am getting this error

object` ("[object Response]") cannot be serialized as JSON

But when I call or use this api through browser I am getting response.

here is my code https://codesandbox.io/s/naughty-platform-1xket?file=/pages/index.js

I am consuming my api like this

 console.log("-----");
  const cc = await fetch("https://1xket.sse.codesandbox.io/api/basecss/");
  console.log(cc, "llll");

API design

export default async (req, res) => {
  const stylesheet = await (
    await fetch("https://www.****.com/asset/web/css/***-base.css", {})
  ).text();
  console.log(stylesheet, "server");
  res.status(200).send(stylesheet);
};

I am getting this console value on server. but when I am calling this api through code I am getting this error

object` ("[object Response]") cannot be serialized as JSON. Please only return JSON serializable data types

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You're getting that error because you're returning a response object (cc) in your getStaticProps which is not serializable. getStaticProps and getServerSideProps only allow serializable content to be returned from them.

To fix the issue you'll first need to convert the response data to text before you can return it. You'll also need to change your props to match the ones expected in the IndexPage component.

// pages/index.js

export async function getStaticProps() {
    const res = await fetch("https://1xket.sse.codesandbox.io/api/basecss/");
    const stylesheet = await res.text(); // Converts response data to text

    return {
        props: {
            stylesheet // Changes prop name from `cc` to `stylesheet` to match component
        }
    };
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...