0

I'm learning how to build a MERN app.

I have my DB and Express server working fine with Postman. I also have a working HTML form that can write to the db.

I want to now display data from the DB using a javascript Fetch. The problem is I don't know what I'm doing wrong - I keep getting opaque responses.

Front end:

<script>
fetch('http://localhost:4000/items/',  { method: 'GET',
    mode: "no-cors",
    headers: {"Content-Type": "application/json"}
  })
      .then(response => response)

    .then(data => {
    console.log(data);

  });
  </script>

The response is opaque.

Server code snippet:

    server.get("/items", (request, response) => {
// return updated list
dbCollection.find().toArray((error, result) => {
    if (error) throw error;
    response.json(result);
    console.log(result);
});

});

if I go to http://localhost:4000/items/ I can see the data being presented (as JSON)

How do I access this correctly in javascript using the Fetch api?

1 Answers1

0

You have an opaque response because you said mode: ‘no-cors’

Opaque means you can’t see the response.

The mode is there for when you need to send data but not read the response.

You need permission from CORS to see a cross-origin response, and no-cors is a way of telling fetch that you don’t need it (so it shouldn’t throw an error when it doesn’t get it).

———

then(response => response) is entirely pointless. It doesn’t do anything. You’d need to use response.json() to decode the body, but that impossible when you can’t see the body in the first place.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335