Home > Back-end >  Unable to send objects as payload data while making an Fetch API request
Unable to send objects as payload data while making an Fetch API request

Time:06-29

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. The issue is that the node backend is not able to receive this payload data on the backend, req.body returns an empty object. 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,
    });
    
  });}

CodePudding user response:

You can stringify the array of objects before sending. Use 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)
  });
  • Related