matt-p matt-p - 6 months ago 47
JSON Question

Using Fetch API to Access JSON

I am trying to use fetch api to bring back some data, however am unable to map it to the console once I have retrieved it.

fetch('http://jsonplaceholder.typicode.com/users', {
method: 'GET'
}).then(function(response) {
console.log(response)
response.forEach(i => console.log(i.name));
}).catch(function(err) {
console.log(`Error: ${err}` )
});


The error i get is


response.map is not a function


so I tried to parse the response,(ie var data=JSON.parse) which did not work, with the error

SyntaxError: Unexpected token o in JSON at position 1"


Interestingly, when doing the same thing with a XMLHttp request, I was required to parse it, so I would also be interested to know why the difference between these two methods of retrieving the data.

If anyone could point me in the right direction, I would be really grateful.

Answer

The Fetch API returns a response stream in the promise. The response stream is not JSON, so trying to call JSON.parse on it will fail. To correctly parse a JSON response, you'll need to use the response.json function. This returns a promise so you can continue the chain.

fetch('http://jsonplaceholder.typicode.com/users', { 
  method: 'GET'
})
.then(function(response) { return response.json(); })
.then(function(json) {
  // use the json
});