Home > other >  Mongoose response from server is ReadableStream
Mongoose response from server is ReadableStream

Time:07-02

I have an express server that is fetching data from a local MongoDB.

The fetching seems to work and I am able to log the fetched data:

app.get("/getTestData", async (req, res) => {
  const data = await ContentDataSchema.find();
  console.log(`Mongo data: ${data})`);
  res.json(data);
});

This prints on the server console the correct data from DB which is expected to be an array of objects of the ContentDataSchema.

However, when trying to get this data from the client side:

useEffect(() => {
    fetch("http://localhost:7007/getTestData")
      .then((response) => {
        console.log(`RESPONSE ${response.body}`)
        
      })
      .catch((error) => console.log(`SERVER ERROR ${error})`));
  }, []);

Console output from this is RESPONSE [object ReadableStream] And if I tried to to log console.log(RESPONSE ${JSON.stringify(response.body)}) Then the output is just {}. Using Postman I can see the correct expected response calling the same endpoint.

Expected output on the client side would be the actual json from the DB.

CodePudding user response:

To read the JSON response, you have to use the response.json() method. You can refer to the MDN docs about fetch to learn more about it.

    fetch("http://localhost:7007/getTestData")
      .then(response => response.json())
      .then(data => console.log(data));
  • Related