Ajai
Ajai

Reputation: 3500

Using fetch() Webapi

I am trying to see how browser's native webapi fetch() api works. So far I have this: Sample-Code and it works fine. But what I don't understand why is it streaming string which I have to convert to a JSON? I am not sure why would anybody even need to stream a JSON as string through a REST API? I am pretty sure I am missing something here but I am not sure how I should tell fetch() to get the response as JSON and not as a ReadableByteStream which I have to convert to a string and parse it for a JSON.

My Question is this,

  1. Why is a string being streamed here?
  2. How do I tell fetch() to fetch my response as text or json so that I can do response.json() or response.text() as mentioned in the docs? (FYI I tried adding a header object and creating a Header instance and passing it to fetch() neither changed my response.

Upvotes: 1

Views: 479

Answers (2)

Ajai
Ajai

Reputation: 3500

Apparently I have to do response.json() in one then handler and have the actual value in subsequent then handlers. Update-code. What I didn't realize was response.json() returned another Promise which I should handle like a promise. So console.log(response.json()) will naturally just console log a JSON object instead of my actual json. Thank your @aray12 for you answer. I didn't realize the answer until I realize .json() returned a promise.

PS: Adding this as an answer as I couldn't add this in comments.

Upvotes: 0

aray12
aray12

Reputation: 1843

All you need to do is call

fetch("https://api.github.com/users/ajainarayanan").then(res => res.json());

Here is some modified code the has the same result

fetch("https://api.github.com/users/ajainarayanan")
  .then(res => res.json())
  .then(res => console.log('Profile: ', JSON.stringify(res, null, 2)));

Upvotes: 3

Related Questions