Working with JSON and the fetch API [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 4 years ago.
I'm trying to fetch this JSON in my javaScript code using the fetch API:
{
"posts": [
{ "id": 1, "title": "json-server", "author": "typicode" }
]
}
This is my code:
const endpoint = 'http://localhost:3000/posts'
let posts = []
fetch(endpoint)
.then(resp => resp.json())
.then(data => posts.push(...data))
console.log(posts[0])
The console.log gives me undefined on chrome's console, but if I type posts[0] on the same console I get the post object I'm hoping to get.
I'm serving the JSON file with json-server and the .html with the vs code extension live-server.

Related

Data is not pushed in an array [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 1 year ago.
I got data from API and tried to push it in an array, but when I print it, it's empty. The data is JSON.
fetch("url")
.then((response) => response.json())
.then((data) => sohawnID.push(data.id))
console.log(sohawnID)
//output: []```
this is because synchronous behavior of node js. what you need is to put you api call method inside a Promise function and then call it using async await. By this way program 1st wait for api response and then push data to your array
The reason it prints empty is console.log(sohawnID) called before the promise fulfil meaning you are trying to print result before it arrives. You can do this:
fetch("url")
.then((response) => response.json())
.then((data) => {
sohawnID.push(data.id);
console.log(sohawnID)
})
``

Fetch API returning "undefined" [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
I am currently learning how to work with APIs, and I am having a little trouble with fetching the data from an API. The code below successfully gets a response but does not actually get any data from the server. How do I go about solving this?
const onClick = () => {
fetch(
`https://collectionapi.metmuseum.org/public/collection/v1/objects/45734`
)
.then(res => {
if (res.ok) {
console.log(res)
console.log('SUCESSS')
} else {
console.log("Not Successful")
}
})
.then(data => {
if (data) {
console.log(data)
} else {
console.log("undefined data")
}
})
.catch(error => console.log('ERROR'))
console.log(results);
}
The promise .then methods can be chained in a way each chained then methods will receive the returned value of the previous one. In your case, the first one does not return any values, making the second one receiving nothing, also well known as undefined.
As the url your code is calling return json content, you should return after loging success the result of res.json().
This will read the stream of the response body and parse it as json, using a promise.

Promise with fetch returning response [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 2 years ago.
I'm doing some fetches in a promise and then consolidating my results into a response json. When I console.log it, it prints out as expected, but I'm not sure how to return it as the response.
I have something like this:
router.get('/', function(req, res) {
Promise.all([ fetch(url1); fetch(url2); ]);
}.then(function(responses) {
// Consolidate responses into one data json
console.log(data); // Prints correct object
return response; // This doesn't work
}

Cannot retrieve specific JSON data from API call [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
I am trying to use the variable 'myResult' to return specific JSON data. I believe I may have written the 'myResult' variable wrong and I am not querying for the correct data. The path for '[1].show.score'is correct and I will add in screenshots of the JSON data I am trying to call.
When I call for this data, I get returned to me this error:
[![My error][2]][2]
Here is the result of 'url'
[![The returned JSON data from the variable 'url'][1]][1]
Here is my code:
document.querySelector('.myButton').addEventListener('click', function(){
var query = document.getElementById('main').value;
var url = fetch("http://api.tvmaze.com/search/shows?q="+query)
.then(response => response.json())
.then(data => console.log(data));
var myResult = url[1].show.score;
console.log(myResult);
})```
[1]: https://i.stack.imgur.com/lTn8V.png
[2]: https://i.stack.imgur.com/kS7gB.png
You cannot access the data from url the way you are trying to access it with url[1].show.score because url is a promise that you can call .then() and .catch() on, which you already do in order to receive the data.
If you want myResult to use the specific data, you need to use it within the .then() callback
So you may have something like this in the end:
document.querySelector('.myButton').addEventListener('click', function(){
var query = document.getElementById('main').value;
fetch("http://api.tvmaze.com/search/shows?q="+query)
.then(response => response.json())
.then(data => {
console.log(data));
var myResult = data[1].show.score;
console.log(myResult);
}
})

Storing API response into a variable in Node.js with Axios [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
const axios = require('axios');
const exchangeRate;
axios.get('https://kurs.resenje.org/api/v1/currencies/eur/rates/today').then(function(response){
exchangeRate = response.data;
})
function one(){
console.log(exchangeRate);
}
I have code like this. This obviously wont work, but I hope that you get the idea. I tried many solutions online, non of which work. I tried with async await but I always got Promise returned instead of JSON.
Does this work?
async function run() {
const url = 'https://kurs.resenje.org/api/v1/currencies/eur/rates/today'
const response = await axios.get(url)
const exchangeRate = response.data
}
run()

Categories

Resources