繁体   English   中英

发出 Fetch API 请求时无法将对象作为有效负载数据发送

[英]Unable to send objects as payload data while making an Fetch API request

我有一个反应前端和节点后端,我正在使用 Axios 从外部 API 获取对象列表,然后尝试将其传递给我的节点后端。 问题是节点后端无法在后端接收此有效负载数据,req.body 返回一个空对象。 为了调试,我看到了网络选项卡中发生的情况,并观察到有效负载数据只返回数据类型而不是实际数据,如下所示。

在此处输入图像描述这是我的前端代码的样子:

let faqlist = "";
// fetching data from one api
await axiosinstance
  .get(
    "https://linktotheapi/api/faq"
  )
  .then((res) => {
    faqlist = res.data;

    console.log("This is faqlist", faqlist);
    console.log(typeof faqlist);
    // passing the data fetched from 1st api to node/express backend.
    fetch("/create-page", {
      method: "POST",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
      },
      body: faqlist,
    });
    
  });}

您可以在发送之前对对象数组进行stringify 使用JSON.stringify

const x = [{ x: 1 }, { x: 2 }];
  fetch("https://httpbin.org/post", {
    method: "POST",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json"
    },
    body: JSON.stringify(x)
  });

暂无
暂无

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

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