How does data flow work when using the Fetch API? - javascript

Take a simple API fetch call, such as follows:
fetch('https://api.nasa.gov/planetary/apod?api_key=xxxxxxxxx')
.then(res => res.json())
.then(data =>setPic(data.hdurl))
I'm still a bit confused about how this works. My understanding is this - information is sent from the web server as JSON, but to displayed on a web page it has to be converted into a normal JS object. Is this correct?
And if so, how does the above method convert JSON to a JS object? Because as I understand it, res.json simply extracts the JSON, it doesn't convert it.

[...] how does the above method convert JSON to a JS Object? Because
as I understand it, res.json() simply extracts the JSON, it doesn't
convert it.
This is what .json() does - it resolves the JSON string and parses it into a JS Object:
// Retrieves data from a URL
fetch('data:text/plain;charset=utf-8,%7B%22myJSON%22%3A%20%22myJSON%22%7D')
// Resolve the data retrieved from the URL as JSON and parse into a JS Object
.then(res => res.json())
// Work with the resolved data
.then(data => {
console.log('data has been resolved as: ' + typeof data);
console.log(data);
});
If you want the JSON String to remain a JSON String, you can use .text() instead:
// Retrieves data from a URL
fetch('data:text/plain;charset=utf-8,%7B%22myJSON%22%3A%20%22myJSON%22%7D')
// Resolve the data retrieved from the URL as a string
.then(res => res.text())
// Work with the resolved data
.then(data => {
console.log('data has been resolved as: ' + typeof data);
console.log(data);
});

Related

How to fetch dynamic json with respond.json function using javascript [duplicate]

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.
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
});
Understanding promises is key to using the fetch API.
At the time you're trying to parse your response and loop through it, the response is actually just a promise. In order to utilize the contents of the actual response from the request, you'll have to do some promise chaining.
fetch('http://jsonplaceholder.typicode.com/users').then(function(response) {
// response.json() returns a promise, use the same .then syntax to work with the results
response.json().then(function(users){
// users is now our actual variable parsed from the json, so we can use it
users.forEach(function(user){
console.log(user.name)
});
});
}).catch(err => console.error(err));
It appears that you might be accessing the json incorrectly. You could try calling response.json() instead.
fetch('http://jsonplaceholder.typicode.com/users', {
method: 'GET'
}).then((response) => {
response.json().then((jsonResponse) => {
console.log(jsonResponse)
})
// assuming your json object is wrapped in an array
response.json().then(i => i.forEach(i => console.log(i.name)))
}).catch((err) => {
console.log(`Error: ${err}` )
});
This example is structured to match your example, but ideally, you would return response.json() on that first .then block and proceed on the next block. Here is a similar example that proceeds on the next block.
In your particular case, you can view the Fetch API as a json aware wrapper for "XMLHttpRequest"s. Main differences being that the Fetch API is simpler, functional-like, and has convenience methods. David Walsh does a reasonable comparison in his blog post, which I recommend you take a look at. Plain "XMLHttpRequest"s just pass you whatever string was sent back from the server, it has no idea it could be JSON, and thus leaves it to the user to parse the response whatever way they see fit.

Save JSON in Local Storage after the fetch

Sorry if this was posted a lot, I read through several articles but could not find the solution. So, I'm fetching a large JSON from this API, and I would like to cache the response somehow in the localStorage, so the next time the page loads, the scripts first checks if there is an object with the requested ID inside the JSON, and renders the content if there is one - and if there isn't, goes of to the API to fetch it.
I was thinking of setting up two fetch() functions, and this is what I have:
fetch(url + id)
.then((response) => {
localStorage.setItem('myResponse', response);
})
.catch((error) => {
console.log(error);
})
Then, check if there is something saved inside the localStorage, and if it is good, use it to render the HTML, if not, go on to another fetch to get it from the API.
if(localStorage) {
createHTML(localStorage.myResponse);
} else {
fetch(url + id)
.then(response => response.json())
.then(data => createHTML(data))
}
But, in the first fetch, if I use JSON.stringify(response), it just shows it as an empty object, so it the localStorage it looks like: myResponse - {}. If I do console.log(response.json()); on the first fetch, it shows PromiseĀ {<pending>}.
I've tried to make something out of that, but without results...any help much appreciated!
response.json() is a Promise, it needs to be either awaited, or chained a .then(); If you simply log it as is, all you'll get is Promise {<pending>} because it hasn't resolved yet.
fetch(url + id)
.then( response => response.json() )
.then( json => {
localStorage.setItem('myResponse', JSON.stringify(json));
})
Or with the async/await syntax :
const response = await fetch(url + id);
const json = await response.json();
localStorage.setItem('myResponse', JSON.stringify(json));

how to fetch data from promise object which is in json format

I'm trying to calculate distance from google api using fetch now i convert data into json which is in promise object and json fromat here is my code and also the screenshot of what I'm getting now
i try so far but getting undefined error every time.
fetch(proxyurl + re)
.then(function(response) {
console.log (response.json());
});
i want to get data of source and destination time and distance
here is the screenshot https://i.stack.imgur.com/Dz51R.png
Try to update your fetch method like this:
fetch('https://api-endpoint.com')
.then(response => response.json())
.then(data => {
console.log(data);
});
Demo with github users endpoint: https://codesandbox.io/s/prod-bush-wqn70

fetch data from json running on node.js

I want to fetch data from JSON object which is on my localhost .
..This might be really stupid question but I am beginner in JS.
and is there any other way to fetch data ??
fetch('http://localhost:3000/show')
.then(result => {
console.log(result);
return result.json();
});
.then(data => {
console.log(data);
});
.catch(error => {
console.log(error);
});
this http://localhost:3000/show contains json objects.
it has retrieved data from mongoose.
Remove the semicolons between each .then call.
Promises use a kind of "monadic" pattern: each method on a promise returns another promise, which has the same API. This means you can chain promise methods indefinitely.
So:
fetch()
.then(/* stuff */)
.then(/* more stuff */)
.catch(/* even more stuff */); // <-- this is the only semicolon
The same is true of many Array methods, so you'll often see code like this:
Object.keys( someObj ) // returns an array
.map(/* iterator function */) // Array.map returns an array
.filter(/* iterator function */) // Array.filter returns an array
.sort(/* comparator function */); // Array.sort returns an array
Again, only one semicolon is needed, because each step of the statement produces an array, and JS lets you anticipate that.
If that doesn't help, you might want to post the error you're getting.
I should add that result.json() will throw if the server at http://localhost:3000/show fails to provide the HTTP header Content-Type: application/json. Even if the response body is entirely valid JSON, the HTTPResponse class refuses to do .json() if the server doesn't state that the content is json.
Also, if this code is running in a browser, and is served from a different host (or port), you will need to do CORS stuff. See https://stackoverflow.com/a/48287868/814463 for possible help.
If your endpoint '/show' returns the json data without any issue, then the below code should console you the json response.
fetch('http://localhost:3000/show')
.then(res => {
console.log(result);
return res.json()
)}
.then(json => console.log(json))
.catch(err => console.log(err));

How to add "credentials: include" to d3.json method? D3.js

I am trying to use the d3.json method to access JSON Data from an endpoint. I am able to successfully access the data using the fetch method below, however I am not sure how to change this to the d3.json method. How can I pass the argument "credentials:include"
fetch('http://0.0.0.0:example.com',{
credentials: 'include'
})
.then(response => response.json())
.then( json => console.log(json))
My attempt would be something like this, however I am not sure where I would add the credentials argument.
d3.json('http://0.0.0.0:example.com', json => console.log(json))
d3.json use fetch so the same will work
From the doc:
d3.json:
Fetches the JSON file at the specified input URL. If init is specified, it is passed along to the underlying call to fetch; see RequestInit for allowed fields.
d3.json('http://0.0.0.0:example.com', {credentials: "include"}, function(error, json) {
console.log(json);
})

Categories