0

I currently have my own api i am trying to send and retrieve data from. In the api I am trying to send an object to the front-end using something like res.send({data: 1}).

I am easily able to access this data using postman but when trying to fetch the data using - well - fetch, i have no way to acess it. the way I try to fetch it is as follows:

    const response = await fetch("http://localhost:2000/user/login", {
    method: "post",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(user),
  });

And logged response looks like this:

body: (...)
bodyUsed: false
headers: Headers
[[Prototype]]: Headers
ok: true
redirected: false
status: 200
type: "cors"
url: "http://localhost:2000/user/login"
[[Prototype]]: Response

The {data: 1} object is nowhere to be found and i have no clue how to access it.

Is this the wrong way to go about retrieving and sending data from and to an api or am i just overlooking something? What would the best way to transfer data like this be then?

Thanks in advance!

Ps: the {data: 1} is just an example and the real way i would use this at the moment would be to fetch data from an express session cookie.

Atilla
  • 31
  • 3
  • 1
    You can read about Fetch API https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch. I dont see any example for res.send in this document. – Mai Truong Nov 23 '21 at 03:03
  • To elaborate on @MaiTruong's documentation link with a very simple example... `const data = await response.json(); console.log(data)` – Phil Nov 23 '21 at 03:07

1 Answers1

0

fetch() returns a promise whose resolved value gets you the status and headers of the response. You are awaiting that promise so you do get that info. But to read the actual body of the response, you need to make another call to response.json() that returns another promise:

const response = await fetch("http://localhost:2000/user/login", {
  method: "post",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify(user),
});

// read the body of the response
const data = await response.json();
console.log(data);
jfriend00
  • 683,504
  • 96
  • 985
  • 979