object` ("[object Response]") 不能序列化为 JSON? [英] object` ("[object Response]") cannot be serialized as JSON?

查看:187
本文介绍了object` ("[object Response]") 不能序列化为 JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过代码使用我的 api 我收到此错误

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

object`([object Response]")无法序列化为 JSON

但是当我通过浏览器调用或使用这个 api 时,我得到了响应.

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

这是我的代码https://codesandbox.io/s/naughty-platform-1xket?file=/pages/index.js

我正在像这样使用我的 api

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 设计

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

我在服务器上得到这个控制台值.但是当我通过代码调用这个 api 时,我收到了这个错误

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

推荐答案

您收到该错误是因为您在 getStaticPropscc)> 不可序列化.getStaticPropsgetServerSideProps 只允许从它们返回可序列化的内容.

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.

要解决此问题,您首先需要将响应数据转换为文本,然后才能返回.您还需要更改道具以匹配 IndexPage 组件中预期的道具.

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

这篇关于object` ("[object Response]") 不能序列化为 JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆