简体   繁体   English

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

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

I have a react frontend and node backend, I am fetching a list of objects from an external API using Axios and then trying to pass it to my node backend.我有一个反应前端和节点后端,我正在使用 Axios 从外部 API 获取对象列表,然后尝试将其传递给我的节点后端。 The issue is that the node backend is not able to receive this payload data on the backend, req.body returns an empty object.问题是节点后端无法在后端接收此有效负载数据,req.body 返回一个空对象。 To debug, I've seen what happens in the network tab, and have observed that the payload data just returns the data type instead of the actual data as shown below.为了调试,我看到了网络选项卡中发生的情况,并观察到有效负载数据只返回数据类型而不是实际数据,如下所示。

enter image description here Here is what my front-end code looks like:在此处输入图像描述这是我的前端代码的样子:

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

You can stringify the array of objects before sending.您可以在发送之前对对象数组进行stringify Use JSON.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