Reputation: 134
I've been struggling trying to understand how to access and and process data using HTTP method routes (get, put, post...). So far, I've been able to fetch the JSON data and store it in a global variable.
var pokedata;
fetch('https://raw.githubusercontent.com/Biuni/PokemonGO-Pokedex/master/pokedex.json')
.then(function (res) {
return res.json();
}).then(function (json) {
pokedata = json;
}).catch(function () {
console.log("It was not possible to fetch the data.")
});
I wanted to send responses HTTP GETs to http://localhost:3000/pokemon/XXX/
with some data about that Pokémon number XXX (which is in the JSON called pokedata). However, any attempt at looping through the data inside GET, triggers the error:
app.get('/pokemon/:pokemonid', function (req, res) {
//not the desired behaviour but a sample of what doesn't work.
for (let {name: n, weight: w, height: h} of pokedata) {
res.send(n, w, h);
}
});
TypeError: pokedata[Symbol.iterator] is not a function
Can't seem to find anything related in the express docs. Any help is well received.
Upvotes: 1
Views: 680
Reputation: 84902
pokedata
is an object, and you don't want to iterate on it. Instead you want to iterate on pokedata.pokemon
, which is an array of the pokemon. So a small modification to your code is all that's needed:
for (let {name: n, weight: w, height: h} of pokedata.pokemon) {
res.send(n, w, h);
}
Upvotes: 3