Ajai Ajai - 6 months ago 70
JSON Question

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.


Answer

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)));
Comments