0

I have been trying to make a http PUT request for sending data to the server. Each time, when I try to send the request the data in the server becomes null. I have tested the server side code by sending correct format of data seems the server side is working fine. Going back to the client side code, I have noticed that during fetch operation the data in the response becomes in ReadableStream. Don't know actually what does that mean. Can anybody help me finding out the mistakes if it is possible from the below information.

I am trying to send the data from the react component:

updateData(data)

the format of the data I am trying to send is an Object:

{first:"first", second:"second"}

And then in my API handler:

const updateData = async (data) => {
const resource = await getResource('PUT', {
    data,
  });
const url = `${process.env.updateAPI}/Update`;
  return handleFetch(url, resource);
};

And then in my handleFetch function:

  const handleFetch = async (url, resource) => {
  const res = await fetch(url, resource);

  if (!res.ok) {
    throw new Error(`Request failed, status ${res.status}`);
  }

  const resData = await res.json();
  return resData;
};

getResource function is accepting the parameters and returns the required methods, data and the header where 'Content-Type': 'application/json', is provided and handling the data like: body = JSON.stringify(data);

During debugging I have noticed that the res from fetchHandlers becomes like this:

enter image description here

I am actually confused, why in the body the data becomes ReadableStream instead of the actual data I am trying to send or is this the problem I am having null values. Can anybody help me with that?, it will be highly appreciated.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
ninja
  • 167
  • 2
  • 12
  • Does this answer your question? [Retrieve data from a ReadableStream object?](https://stackoverflow.com/questions/40385133/retrieve-data-from-a-readablestream-object) – Striped Sep 27 '20 at 10:47

1 Answers1

1

If your data return type is not JSON or you don't want JSON then use text()

As an example:

fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then(function(response) {
    return response.text();
  }).then(function(data) {
    console.log(data); // this will be a string
  });
Striped
  • 2,544
  • 3
  • 25
  • 31